# -*- encoding: utf-8 -*-
# This file is part of Tryton.  The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.

'''
Inherit stock for endicia API
'''
from decimal import Decimal, ROUND_UP
import base64
import math
import logging

from endicia import ShippingLabelAPI, LabelRequest, RefundRequestAPI, \
    BuyingPostageAPI, Element, CalculatingPostageAPI
from endicia.tools import objectify_response, get_images
from endicia.exceptions import RequestError

from trytond.model import Workflow, ModelView, fields
from trytond.wizard import Wizard, StateView, Button
from trytond.transaction import Transaction
from trytond.pool import Pool, PoolMeta
from trytond.pyson import Eval, Bool
from trytond.rpc import RPC

from .sale import ENDICIA_PACKAGE_TYPES, MAILPIECE_SHAPES


__metaclass__ = PoolMeta
__all__ = [
    'ShipmentOut', 'ShippingEndicia', 'GenerateShippingLabel',
    'EndiciaRefundRequestWizardView', 'EndiciaRefundRequestWizard',
    'BuyPostageWizardView', 'BuyPostageWizard',
]

STATES = {
    'readonly': Eval('state') == 'done',
}

logger = logging.getLogger(__name__)

quantize_2_decimal = lambda v: Decimal(v).quantize(
    Decimal('.01'), rounding=ROUND_UP
)


class ShipmentOut:
    "Shipment Out"
    __name__ = 'stock.shipment.out'

    endicia_mailclass = fields.Many2One(
        'endicia.mailclass', 'MailClass', states=STATES, depends=['state']
    )
    endicia_mailpiece_shape = fields.Selection(
        MAILPIECE_SHAPES, 'Endicia MailPiece Shape', states=STATES,
        depends=['state']
    )
    endicia_shipment_bag = fields.Many2One(
        'endicia.shipment.bag', 'Endicia Shipment Bag')
    endicia_label_subtype = fields.Selection([
        ('None', 'None'),
        ('Integrated', 'Integrated')
    ], 'Label Subtype', states=STATES, depends=['state'])
    endicia_integrated_form_type = fields.Selection([
        (None, ''),
        ('Form2976', 'Form2976(Same as CN22)'),
        ('Form2976A', 'Form2976(Same as CP72)'),
    ], 'Integrated Form Type', states=STATES, depends=['state'])
    endicia_include_postage = fields.Boolean(
        'Include Postage ?', states=STATES, depends=['state']
    )
    endicia_package_type = fields.Selection(
        ENDICIA_PACKAGE_TYPES, 'Package Content Type',
        states=STATES, depends=['state']
    )
    is_endicia_shipping = fields.Function(
        fields.Boolean('Is Endicia Shipping?', readonly=True),
        'get_is_endicia_shipping'
    )
    endicia_refunded = fields.Boolean('Refunded ?', readonly=True)

    @classmethod
    def view_attributes(cls):
        return super(ShipmentOut, cls).view_attributes() + [
            ('//page[@id="endicia"]', 'states', {
                'invisible': ~Bool(Eval('is_endicia_shipping'))
            })]

    def _get_weight_uom(self):
        """
        Returns uom for endicia
        """
        UOM = Pool().get('product.uom')

        if self.is_endicia_shipping:

            # Endicia by default uses this uom
            return UOM.search([('symbol', '=', 'oz')])[0]

        return super(ShipmentOut, self)._get_weight_uom()

    @staticmethod
    def default_endicia_mailclass():
        Config = Pool().get('sale.configuration')
        config = Config(1)
        return config.endicia_mailclass and config.endicia_mailclass.id or None

    @staticmethod
    def default_endicia_label_subtype():
        Config = Pool().get('sale.configuration')
        config = Config(1)
        return config.endicia_label_subtype

    @staticmethod
    def default_endicia_integrated_form_type():
        Config = Pool().get('sale.configuration')
        config = Config(1)
        return config.endicia_integrated_form_type

    @staticmethod