"""
    starfish.provenance contract

"""

from convex_api.contract import Contract

from convex_api.utils import (
    add_0x_prefix,
    is_address,
    to_address
)

from starfish.network.convex.convex_account import ConvexAccount
from starfish.types import AccountAddress


class ProvenanceContract(Contract):

    def register_provenance(self, asset_id: str, data: str, account: ConvexAccount):
        quote_data = Contract.escape_string(data)
        command = f'(register {add_0x_prefix(asset_id)} "{quote_data}")'
        result = self.send(command, account)
        if result and 'value' in result:
            return {
                'timestamp': result['value']['timestamp'],
                'owner': to_address(result['value']['owner']),
            }
        return result

    def event_list(self, asset_id: str, account_address: AccountAddress):
        command = f'(event-list {add_0x_prefix(asset_id)})'
        if is_address(account_address):
            address = account_address
        else:
            address = account_address.address
        result = self.query(command, address)
        if result and 'value' in result:
            return ProvenanceContract.convert_event_list(result['value'])
        return result

    def owner_asset_list(self, account_address: AccountAddress):
        if is_address(account_address):
            address = account_address
        else:
            address = account_address.address
        command = f'(owner-list {address})'
        result = self.query(command, address)
        if result and 'value' in result:
            return result['value']
        return result

    @staticmethod
    def convert_event_list(items):
        event_list = []
        for item in items:
            event_list.append({
                'timestamp': item['timestamp'],
                'owner': to_address(item['owner']),
            })
        return event_list
