import logging,os
from tixsell import settings
import requests
from web3 import Web3
logger = logging.getLogger('django')


def signal_updateuser(sender,**kwargs):
    if kwargs['created']: return None
    #check if field modified is walletAddress
    logger.info("=====SIgnal update user ")
    logger.info(kwargs)
    user = kwargs['instance']
    if user.walletAddress:
        
        #try to find tickets without refUser and having this walletAddress
        try:
            from backoffice.models import Ticket
            theTicket = Ticket.objects.get(lastOwner=user.walletAddress,refUser=None)
            #if found, update refUser
            theTicket.refUser=user
            theTicket.save()
        except Exception as error:
            pass

def signal_modifEvent(sender,**kwargs):
    if kwargs['created']: return None
    try:
        theEvent = kwargs['instance']
        if theEvent.status==1 and theEvent.webHookSet==False and theEvent.ticketContract:
            #Alchemy webhook replace by our NFTMonitormanager
            """
            #pass todo create webhook 
            url = "https://dashboard.alchemy.com/api/create-webhook"

            payload = {
                "network": settings.NETWORK,
                "webhook_type": "NFT_ACTIVITY",
                "webhook_url": "https://api.selltix.live/webhook/",
                "nft_filters": [{ "contract_address": theEvent.ticketContract }]
            }
            headers = {
                "accept": "application/json",
                "X-Alchemy-Token": settings.AlchemyTokenWebHook,
                "content-type": "application/json"
            }

            response = requests.post(url, json=payload, headers=headers)
            if response.status_code==200:
                logger.info("===On set webhook pour event %s"%theEvent.name)
                import json
                logger.info(response.text) 
                # response.text is a json, transform to a json variable
                json_data = json.loads(response.text)
                theEvent.webHookSet=True
                theEvent.alchemyWebHookId = json_data["data"]["id"]
                theEvent.save()
            """
            # Maintenant il update tous les ticketsType de value -1 
            try:
                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()
                    for theTicketType in ticketsTypeQuery:
                        # on va chercher information sur la blockchain 
                        logger.info("==== On doit aller chercher info ticketTypeId sur la blockchain pour event ticketTypeContract %s"%theTicketType.id)
                     
                        for aTicketType in ticketTypes:
                            name = aTicketType[19]
                            price = aTicketType[3]
                            startDate = aTicketType[4]
                            finalPrice = w3.from_wei(price,'ether')
                            logger.info("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):
                                logger.info("===On a trouve ticket type")
                                theTicketType.ticketTypeId = aTicketType[0]
                                theTicketType.status=1
                                theTicketType.save()
                                break
            except Exception as e:
                logger.info(e)
    except Exception as e:
        logger.info(e)

def signal_publishTicketType(sender,**kwargs):
    if kwargs['created']:
        return None
    try:
        theTicketType = kwargs['instance']
        if theTicketType.status==1 and theTicketType.ticketTypeId==-1:
            # on va chercher information sur la blockchain 
            #BUG l'event n'a pas encore été mis à jour... 
            logger.info("==== On doit aller chercher info ticketTypeId sur la blockchain pour event ticketTypeContract %s"%theTicketType.refEvent.ticketTypeContract)
            from tixsell.settings import TICKET_TYPE_ABI
            # Initialize contract ABI and address
            # Create smart contract instance
            w3 = Web3(Web3.HTTPProvider(settings.CONTRACT_NODE_URL))
            checkedTicketTypeAddress = w3.to_checksum_address(theTicketType.refEvent.ticketTypeContract)
            contract = w3.eth.contract(address=checkedTicketTypeAddress, abi=TICKET_TYPE_ABI)
            ticketTypes = contract.functions.fetchTicketsType().call()
            for aTicketType in ticketTypes:
                name = aTicketType[19]
                price = aTicketType[3]
                startDate = aTicketType[4]
                finalPrice = w3.from_wei(price,'ether')
                logger.info("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):
                    logger.info("===On a trouve ticket")
                    theTicketType.ticketTypeId = aTicketType[0]
                    theTicketType.save()
                    break
    except Exception as e:
        logger.info(e)