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

from tixsell import settings


def run():
                theEvent = Event.objects.get(id="64fa23cb-3682-43b0-bad8-be2f82d5c86c")
                from backoffice.models import TicketType
                ticketsTypeQuery = TicketType.objects.filter(refEvent=theEvent,status=0,ticketTypeId=-1)
                if ticketsTypeQuery.exists():
                     # Initialize contract ABI and address
                    # Create smart contract instance
                    from tixsell.settings import TICKET_TYPE_ABI
                    w3 = Web3(Web3.HTTPProvider(settings.CONTRACT_NODE_URL))
                    checkedTicketTypeAddress = w3.to_checksum_address(theEvent.ticketTypeContract)
                    contract = w3.eth.contract(address=checkedTicketTypeAddress, abi=TICKET_TYPE_ABI)
                    ticketTypes = contract.functions.fetchTicketsType().call()
                    try:
                        for theTicketType in ticketsTypeQuery:
                            # on va chercher information sur la blockchain 
                            print("==== On doit aller chercher info ticketTypeId sur la blockchain pour event ticketTypeContract %s"%theTicketType.id)
                        
                            for aTicketType in ticketTypes:
                                print(aTicketType)
                                name = aTicketType[18]
                                price = aTicketType[3]
                                startDate = aTicketType[4]
                                finalPrice = w3.from_wei(price,'ether')
                                print("Compare %s %d %d avec %s %s %s"%(name,startDate,price,theTicketType.name,int(theTicketType.bookingStartDate.timestamp()),theTicketType.ticketPrice))
                                if name == theTicketType.name and startDate==int(theTicketType.bookingStartDate.timestamp()) and int(finalPrice)==int(theTicketType.ticketPrice):
                                    print("===On a trouve ticket")
                                    theTicketType.ticketTypeId = aTicketType[0]
                                    theTicketType.status=1
                                    theTicketType.save()
                                    break
                    except Exception as e:
                                print(e)