"""
Copyright 2019 de la Dirección General de Sistemas Informáticos – Secretaría Legal y Técnica - Nación.

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/
"""
import json

from django.core.management.base import BaseCommand
import logging
import getpass

from gateway.gateway import ContractDeployer, Gateway, HTTPProviderGenerator

logger = logging.getLogger('cmd-logger')


class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('--node_url', help="Node URL", type=str)
        parser.add_argument('--is_poa', help="Is POA network", action='store_false')
        parser.add_argument('--account', help='Account a usar', action=str)
        parser.add_argument('--bytecode', help='Path del bytecode', action=str)
        parser.add_argument('--abi.json', help='Path del abi.json', action=str)
        parser.add_argument('--gas', help='Gas a usar', action=int)
        parser.set_defaults(node_url=None, account=None, bytecode=None, abi=None, gas=None, is_poa=False)

    def handle(self, *args, **options):
        try:
            if options['node_url'] is None:
                options['node_url'] = input("Ingrese la url del nodo")

            provider = HTTPProviderGenerator(options['node_url'])
            gateway = Gateway(provider, options['is_poa'])
            self.stdout.write(str(gateway.get_node_accounts()))
            if options['account'] is None:
                options['account'] = input('Ingrese el owner account: ')

            if options['account'] is None:
                raise Exception("No fue ingresado owner account")

            passphrase = getpass.getpass('Ingrese el passphrase: ')
            unlocked = gateway.unlock_account(options['account'], passphrase)  # TODO Pedir por prompt
            if not unlocked:
                raise Exception("Contraseña incorrecta")
            bytecode_file = options['bytecode']
            if bytecode_file is None:
                bytecode_file = input('Ingrese el file path del bytecode: ')
            if bytecode_file is None:
                raise Exception("No fue ingresado file path del bytecode")
            with open(bytecode_file, 'r') as myfile:
                bytecode = myfile.read().replace('\n', '')
            abi_file = options['bytecode']
            if abi_file is None:
                abi_file = input("Ingrese file path del abi_nuevo: ")
            if abi_file is None:
                raise Exception("No fue ingresado file path del abi_nuevo")
            with open(abi_file) as json_file:
                abi = json.dumps(json.load(json_file))

            deployer = ContractDeployer(gateway)

            gas = deployer.estimate_deploy(abi, bytecode)
            logger.info("Gas estimado: {}".format(str(gas)))
            if options['gas'] is not None:
                gas_aux = options['gas']
            else:
                gas_aux = input("Ingrese un límite de gas opcional: ")
            if gas_aux is not '':
                gas = int(gas_aux)

            tx_receipt = deployer.deploy_contract(abi, bytecode, gas, True)
            logger.info("Contract address: {0}".format(tx_receipt['contractAddress']))
            logger.info("tx_receipt: {}".format(str(tx_receipt)))
        except Exception as e:
            logger.exception(e)