from ..exchange import Exchange
from ..commoditys import commoditys as cm
from lightmatchingengine.lightmatchingengine import Side






class Cell:
    """
    A cell is the basic procedual structure of this simulation. If a cell contains pop then this Cell will have a local market.
    If the cell is contained in a province then the cell will have a 
    """
    name=None # Unique ID/Name of the cell
    loc_x=0
    loc_y=0
    area=1
    pop=0 # Population of the cell
    demand_tags=[] # Demands by 1 pop
    world_tags=[] # Resources provided by cell each episode
    demand={}
    world={}
    exchange: None

    def __init__(self,name,x,y,area,pop,demand,world) -> None:
        pop=pop*100
        self.name=name
        self.loc_x=x
        self.loc_y=y
        self.area=area
        self.pop=pop
        self.demand_tags=demand
        self.demand={}
        self.world_tags=world
        self.world={}

        if pop>0:
            self.exchange=Exchange()
        # build per person demand
        for tag in self.demand_tags:
            d=cm.demand_tags[tag]
            for dem in d:
                k=list(dem.keys())[0]
                v=dem[k]
                if k not in self.demand:
                    self.demand[k]=v*pop
                else:
                    self.demand[k]+=v*pop
        for tag in self.world_tags:
            d=cm.world_tags[tag]
            for wor in d:
                k=list(wor.keys())[0]
                v=wor[k]
                if k not in self.world:
                    self.world[k]=v*area
                else:
                    self.world[k]+=v*area
        
    def setup_demand_for_step(self,episode_length):
        pop_per_step=self.pop/episode_length 
        for demand_key,value in self.demand.items():
            qty=value/episode_length
            comm=cm.commoditys[demand_key]
            max_price=comm["max_world_price"]*qty
            self.exchange.add_to_account(self.name,"balance",max_price)
            self.exchange.submit_order(self.name,demand_key,qty,comm["max_world_price"],Side.BUY)
    def setup_supply_for_episode(self):
        self.exchange.reset()
        for supply_key,value in self.world.items():
            self.exchange.add_to_account(self.name,supply_key,value)
            self.exchange.submit_order(self.name,supply_key,value,1,Side.SELL)



def create_cells_from_world_cells(cells) -> list:
    """
    Creates cells based on a list of cells provided from a world
    """
    ret_cells=[]
    # For now make it very simple
    for i in cells:
        cell=Cell(i["i"],i["p"][0],i["p"][1],i["area"],i["pop"],["basic"],["grass"])
        ret_cells.append(cell)

    return ret_cells
