from trytond.model import ModelSQL, ModelView, fields
from trytond.pool import PoolMeta, Pool
from trytond.exceptions import UserError
from trytond.modules.purchase_trade.purchase import (TRIGGERS)
from trytond.transaction import Transaction
from decimal import getcontext, Decimal, ROUND_HALF_UP

class PartyExecution(ModelSQL,ModelView):
    "Party Execution"
    __name__ = 'party.execution'

    party = fields.Many2One('party.party',"Party")
    area = fields.Many2One('country.region',"Area")
    percent = fields.Numeric("% targeted")
    achieved_percent = fields.Function(fields.Numeric("% achieved"),'get_percent')

    def get_percent(self,name):
        return 2

class PartyExecutionSla(ModelSQL,ModelView):
    "Party Execution Sla"
    __name__ = 'party.execution.sla'

    party = fields.Many2One('party.party',"Party")
    reference = fields.Char("Reference")
    product = fields.Many2One('product.product',"Product")
    date_from = fields.Date("From")
    date_to = fields.Date("To")
    places = fields.One2Many('party.execution.place','pes',"")

class PartyExecutionPlace(ModelSQL,ModelView):
    "Party Sla Place"
    __name__ = 'party.execution.place'

    pes = fields.Many2One('party.execution.sla',"Sla")
    location = fields.Many2One('stock.location',"Location")
    cost = fields.Numeric("Cost",digits=(16,4))
    currency_unit = fields.Selection('get_currency_unit',string="Curr/Unit")

    @staticmethod
    def get_currency_unit():
        Currency = Pool().get('currency.currency')
        Uom = Pool().get('product.uom')

        result = []
        currencies = Currency.search([('concatenate','=',True)])
        units = Uom.search([('concatenate','=',True)])
        result.append(("0_5","USC/lb"))
        result.append(("0_37","USC/mt"))
        for c in currencies:
            for u in units:
                key = "%s_%s" % (c.id, u.id)
                value = "%s / %s" % (c.name, u.symbol or u.name)
                result.append((key, value))
        return result

class Party(metaclass=PoolMeta):
    __name__ = 'party.party'

    tol_min = fields.Numeric("Tol - in %")
    tol_max = fields.Numeric("Tol + in %")
    wb = fields.Many2One('purchase.weight.basis',"Weight basis")
    association = fields.Many2One('purchase.association',"Association")
    execution = fields.One2Many('party.execution','party',"")
    sla = fields.One2Many('party.execution.sla','party', "Sla")

    def IsAvailableForControl(self,sh):
        return True
    
    def get_sla_cost(self,location):
        if self.sla:
            for sla in self.sla:
                SlaPlace = Pool().get('party.execution.place')
                sp = SlaPlace.search([('pes','=', sla.id),('location','=',location)])
                if sp:
                    return round(((sp[0].cost / Decimal(100)) * Decimal(2.2046)),4)
    
    @classmethod
    def getPartyByName(cls, party, category=None):
        party = party.upper()
        p = cls.search([('name', '=', party)], limit=1)
        if p:
            return p[0]
        else:
            p = cls()
            p.name = party
            cls.save([p])
            if category:
                Category = Pool().get('party.category')
                cat = Category.search(['name','=',category])
                if cat:
                    PartyCategory = Pool().get('party.party-party.category')
                    pc = PartyCategory()
                    pc.party = p.id
                    pc.category = cat[0].id
                    PartyCategory.save([pc])
            return p
    