# coding: utf8
from __future__ import unicode_literals
import logging

from django.contrib.auth.models import User
from eth_account.messages import defunct_hash_message
from web3 import Web3
from tixsell.settings import TICKET_ABI
from tixsell import settings
import io
import os
from web3.middleware import geth_poa_middleware
def get_bytes_value(image):
    img_byte_arr = io.BytesIO()
    image.save(img_byte_arr, format='PNG')
    return img_byte_arr.getvalue()

def run():
    web3 = Web3(Web3.HTTPProvider(settings.CONTRACT_NODE_URL))
    DEBUG = os.getenv("DEBUG")
    if DEBUG:
        web3.middleware_onion.inject(geth_poa_middleware, layer=0)
    # Initialize the address calling the fOunctions/signing transactions
    ticketContract="0x0de746e01ad3715642e146B489ae94f8fd8A4a43"
    reservationId ="3befe873-48ba-4b99-ba0d-1fe7888254cfgjgf24"
    amount = 1
    ticketTypeId=1
    # Initialize contract ABI and address
    checkedWalletAddress = web3.to_checksum_address(settings.SELLTIX_WALLET) 
    # Create smart contract instance
    checkedTicketAddress = web3.to_checksum_address(ticketContract)
    contract = web3.eth.contract(address=checkedTicketAddress, abi=TICKET_ABI)
    # : call 
    nonce = web3.eth.get_transaction_count(checkedWalletAddress)
    gas_estimate = contract.functions.createReservation(reservationId,ticketTypeId,amount).estimate_gas()
    print(f'Gas estimate to transact with createReservation: {gas_estimate}')
    transaction = contract.functions.createReservation(reservationId,ticketTypeId,amount).build_transaction({
        'from': checkedWalletAddress,
        'nonce': nonce
    }) 
    private_key = settings.SELLTIX_PRIVATE_KEY
    signed_txn = web3.eth.account.sign_transaction(transaction, private_key=private_key)
    receipt = web3.eth.send_raw_transaction(signed_txn.rawTransaction)
    print ('preview trx hash (trx could be in pending status)', web3.to_hex(web3.keccak(signed_txn.rawTransaction)))
    # blocking: Wait for the transaction to be mined, and get the transaction receipt
    print('receipt with confirmed trx hash (after trx executed)', web3.eth.wait_for_transaction_receipt(receipt))
