# standard imports
import os
import logging

# external imports
from giftable_erc20_token import GiftableToken
from chainlib.eth.tx import (
        TxFactory,
        TxFormat,
        )
from chainlib.eth.contract import (
        ABIContractEncoder,
        ABIContractType,
        )


# local imports
from ge_capped_token.data import data_dir

logg = logging.getLogger(__name__)

class CappedToken(GiftableToken):

    __abi = None
    __bytecode = None

    def constructor(self, sender_address, name, symbol, decimals, tx_format=TxFormat.JSONRPC, version=None):
        code = self.cargs(name, symbol, decimals)
        tx = self.template(sender_address, None, use_nonce=True)
        tx = self.set_code(tx, code)
        return self.finalize(tx, tx_format)


    @staticmethod
    def cargs(name, symbol, decimals, version=None):
        code = CappedToken.bytecode(version=version)
        enc = ABIContractEncoder()
        enc.string(name)
        enc.string(symbol)
        enc.uint256(decimals)
        args = enc.get()
        code += args
        logg.debug('constructor code: ' + args)
        return code

    @staticmethod
    def abi():
        if CappedToken.__abi == None:
            f = open(os.path.join(data_dir, 'CappedToken.json'), 'r')
            CappedToken.__abi = json.load(f)
            f.close()
        return CappedToken.__abi


    @staticmethod
    def bytecode(version=None):
        if CappedToken.__bytecode == None:
            f = open(os.path.join(data_dir, 'CappedToken.bin'))
            CappedToken.__bytecode = f.read()
            f.close()
        return CappedToken.__bytecode