# coding: utf8
from __future__ import unicode_literals
import logging
 
from backoffice.models import Ticket,User
from eth_account.messages import defunct_hash_message
from web3 import Web3

from tixsell import settings


def run():
    ticketContract="0x0de746e01ad3715642e146B489ae94f8fd8A4a43"
    w3 = Web3(Web3.HTTPProvider(settings.CONTRACT_NODE_URL))
    # Initialize the address calling the functions/signing transactions
    
    # Initialize address nonce
    #organizer = Web3.toChecksumAddress(caller)
    #nonce = w3.eth.get_transaction_count(organizer)
    wallet = "0xB3F37E15d98E948DAF68819a21C6802ef34F1c23"
    refTicketType = "e49b157c-c3aa-44ad-82cd-e1e9fe95d987"
    transactionHash="0x9a284c709d643d6576d48c0c76434b6b62169a8e486d6189d5da108ff94d41ba"
    from tixsell.settings import TICKET_ABI
    # Initialize contract ABI and address
    checkedWalletAddress = w3.to_checksum_address(wallet) 
    # Create smart contract instance
    checkedTicketAddress = w3.to_checksum_address(ticketContract)
    contract = w3.eth.contract(address=checkedTicketAddress, abi=TICKET_ABI)
    
    user = User.objects.get(id="a93ec75f-e7e1-4b9d-956f-7a1cd12287a5",walletAddress__icontains=wallet)
    tickets = contract.functions.fetchTicketsForOwner(checkedWalletAddress).call()
    userTickets = Ticket.objects.filter(refUser=user)
    for ticketBlockchain in tickets:
                    """
                    uint256 ticketId;
                    uint256 ticketTypeId;
                    address owner;
                    bytes32 hashedTicket; // EventId:TicketType:TicketId encrypté en SHA256
                    uint256 pricePaid;
                    uint256 purchasedDate;
                    bool used;
                    bool exists;
                    """
                    ticketId=ticketBlockchain[0]
                   
                    hashedTicket = ticketBlockchain[3] 
                    result = bytearray(hashedTicket)  # for testing
                    hxstr = "".join(["{:02x}".format(v) for v in result])
                    finalTicketCode="0x"+hxstr
                    pricePaid = ticketBlockchain[4]
                    #convert to human format 
                    finalPrice = w3.from_wei(pricePaid,'ether')
                    purchasedDate = ticketBlockchain[5]
                    import datetime
                    createdAt = datetime.datetime.fromtimestamp(purchasedDate)
                   
                    needToCreate = True
                    for userTicket in userTickets:
                        print("====Ticket utilisateur %s %s"%(userTicket,userTicket.id))
                        print("===Compoarte %d et %d"%(userTicket.ticketId,ticketId))
                        #pour le meme contrat !!!
                        if userTicket.ticketId==ticketId and userTicket.refTicketType.refEvent.ticketContract==ticketContract:
                            needToCreate=False
                            break
                    if needToCreate==True:
                        print("==On doit cree")
                        newTicket = Ticket()
                        newTicket.refUser = user
                        newTicket.ticketId = ticketId
                        newTicket.refTicketType_id = str(refTicketType)
                        newTicket.lastOwner = wallet
                        newTicket.hashedTicket = finalTicketCode
                        newTicket.pricePaid = finalPrice 
                        newTicket.createdAt = createdAt
                        newTicket.transactionHash = transactionHash
                        newTicket.save()
        
