from .base_business import Business
from ..agents.price_believe_aquire import Price_Believe_Aquire_Agent
from ..agents.price_believe_distribute import Price_Believe_Distribiute_Agent
from ..agents.autoproduction import AutoProductionAgent
import log


class Price_Believe_Business(Business):
    def __init__(self, id, production, balance, exchange, simulation, location) -> None:
        super().__init__(id, production, balance, location)

        self.max_storage = 10
        self.expense_per_unit = -1
        self.income_per_unit = -1
        self.distribute = Price_Believe_Distribiute_Agent(
            simulation, self, production["name"], exchange, 0.2, 50)
        self.craft = AutoProductionAgent(simulation, self)
        self.aquire = {}

        for k, v in production["prod"].items():
            a = Price_Believe_Aquire_Agent(
                simulation, self, k, exchange, 0.2, 5)
            a.set_target(v*2)
            a.set_price_max(10)
            self.aquire[k] = a
        self.distribute.set_price_min(0)
        self.distribute.set_target(0)

    def tick_business_decisions(self, step):
        amount= self.production["amount"]
        if step == 0:

            max_amount = self.production["amount"]*5
            self.craft.set_target(max_amount)
        # Update bookkeeping
        self.update_ex_per_unit()
        self.update_income_per_unit(step)

        # calc descision
        orderForNewProds = self.max_storage
        if self.income_per_unit<=0 or self.expense_per_unit<=0:
            # dont have data
            retain=0
        else:
          ie = (self.income_per_unit/self.expense_per_unit)-1
          if ie < 0:
              ie = 0
          if ie > 1:
              ie = 1
          retain=((self.max_storage-ie*self.max_storage)*amount)-amount
          #retain=0


        # set target for aquire

        prod = self.production["prod"]

        for k, v in prod.items():
            self.aquire[k].set_target(v*orderForNewProds)

        # update production
        targetUnit = self.production["amount"]*orderForNewProds
        self.craft.set_target(targetUnit)

        # set min distribute
        self.distribute.set_price_min(self.expense_per_unit)
        self.distribute.set_target(retain)

    def tick_business_episode(self, episode_count):
        start_balance = self.balance_history[-1]
        diff = self.balance-start_balance

    def resource_in_possesion(self):
        return self.distribute.open_qty+self.inventory[self.production["name"]]

    def update_ex_per_unit(self):
        experunit = 0
        prod = self.production["prod"]
        amount = self.production["amount"]
        qtyNewProds = -1
        for key, agent in self.aquire.items():
            agent.update_trades()
            if agent.qty == 0:
                return
            if agent.qty < 0:
                print("pla")
            req = prod[key]

            covers = agent.qty/req

            if qtyNewProds == -1:
                qtyNewProds = covers
            if qtyNewProds > covers:
                qtyNewProds = covers

            ExPerProd = agent.expense/covers
            experunit += ExPerProd/amount

        if qtyNewProds > 0:
            # confirm new units
            for key, agent in self.aquire.items():
                qtyToConfirm = prod[key]*qtyNewProds
                agent.confirm_purchase(qtyToConfirm)
                a = 1+2

        qtyNewUnits = qtyNewProds*amount

        # if we havent set the expense_per_unit
        if self.expense_per_unit == -1:
            self.expense_per_unit = experunit
            return
        # update expense per unit
        prev_ex_total = self.expense_per_unit*self.resource_in_possesion()
        new_ex_total = qtyNewUnits*experunit
        ex_total = prev_ex_total+new_ex_total
        estimatedQTYUnits = qtyNewUnits+self.resource_in_possesion()
        new_ex = ex_total/estimatedQTYUnits
        self.expense_per_unit = new_ex

    def update_income_per_unit(self, step):
        qty_sold = self.distribute.qty
        income = self.distribute.income
        if income == 0:
            return
        self.income_per_unit = qty_sold/income
        self.distribute.confirm_distribution(qty_sold, step)
        a=self.distribute.trade_curser

    def close_business(self):
        for k, a in self.aquire.items():
            a.unregister()
        self.distribute.unregister()
        self.craft.unregister()

    def log(self, episode, episode_length, step):
        data = {}
        data["id"] = self.id
        data["episode"] = episode
        data["step"] = step
        data["tstep"] = step+episode*episode_length
        data["production"] = self.production["name"]
        data["expense"] = self.expense_per_unit
        data["income"] = self.income_per_unit
        data["inventory"] = self.inventory[self.production["name"]]
        data["retain"] = self.distribute.target
        data["balance"] = self.balance
        data["location"] = self.location
        log.BUSINESSData.append(data)
