import datetime
from pnwapi.exceptions import pnwapiException


class Tradeprice():
    def __init__(self, tradeprice_dict:dict = None):
        from pnwapi import CACHE_EXPIRE_AFTER
        self._cache_expire_after = CACHE_EXPIRE_AFTER
        self.tradeprice_dict = tradeprice_dict

        if tradeprice_dict == None:
            raise pnwapiException("<tradeprice_dict_dict> cannot be none.")
        if not isinstance(tradeprice_dict,  dict):
            raise TypeError("<tradeprice_dict_dict> needs to be a dict called from 'Get().tradeprice(nation_id)'.")
        if not 'resource' in tradeprice_dict:
            raise pnwapiException("<tradeprice_dict> needs to be a dict called from 'Get().tradeprice(resource)'.")

        
        self.all = tradeprice_dict
        self.cache_age = float(tradeprice_dict['cache_age'])


        self.resource = str(tradeprice_dict['resource'])
        self.average_price = int(tradeprice_dict['avgprice'])
        self.market_index = int(tradeprice_dict['marketindex'].replace(",",""))


        self.high_date = datetime.datetime.strptime(tradeprice_dict['highestbuy']['date'], '%Y-%m-%d %H:%M:%S')
        self.high_nation_id = int(tradeprice_dict['highestbuy']['nationid'])
        self.high_amount = int(tradeprice_dict['highestbuy']['amount'])
        self.high_price = int(tradeprice_dict['highestbuy']['price'])
        self.high_price_total = int(tradeprice_dict['highestbuy']['totalvalue'])


        self.low_date = datetime.datetime.strptime(tradeprice_dict['lowestbuy']['date'], '%Y-%m-%d %H:%M:%S')
        self.low_nation_id = int(tradeprice_dict['lowestbuy']['nationid'])
        self.low_amount = int(tradeprice_dict['lowestbuy']['amount'])
        self.low_price = int(tradeprice_dict['lowestbuy']['price'])
        self.low_price_total = int(tradeprice_dict['lowestbuy']['totalvalue'])


    async def get(self, query:str):
        """Get a value from the dictionary based on the raw key
        names in the API returned json."""
        return self.tradeprice_dict[query]

    def __str__(self):
        return self.tradeprice_dict['resource']

    def __repr__(self):
        return f"Nation(nation_dict={self.nation_dict})"