# -*- coding: utf-8 -*-
import base64
import logging
import time
from xml.etree import cElementTree as eTree

from old_helper import OrderTaker
from pos_model import OrderKey
from posot import OrderTakerException

from nfcedisabler import (
    NfceDisabler,
    OrderRepository,
)
from requests.exceptions import RequestException
from services import OrderService

logger = logging.getLogger("FiscalWrapperNfceDisabler")


class OrderDisabler(object):

    def __init__(
        self,
        order_repository,   # type: OrderRepository
        nfce_disabler,      # type: NfceDisabler
        order_taker,        # type: OrderTaker
    ):
        # type: (...) -> None

        self.order_repository = order_repository
        self.nfce_disabler = nfce_disabler
        self.order_taker = order_taker

        self.order_service = OrderService(mb_context=order_repository.mbcontext)

    def disable_all_orders(
        self,   # type: OrderDisabler
    ):
        # type: (...) -> None

        logger.info("Inutilizando notas")
        order_keys = self.order_repository.get_all_orders_to_disable()
        logger.info("Orders para inutilizar: {0}".format(len(order_keys)))

        for order_key in order_keys:  # type: OrderKey
            pos_id = order_key.pos_id
            try:
                logger.info("Inutilizando posId/orderId: {}/{}".format(pos_id, order_key.order_id))
                order_xml = self.order_taker.get_order_picture(pos_id, order_key.order_id)

                logger.info("Iniciando inutilização da order {0} do pos {1}".format(order_key.order_id, pos_id))
                xml = self.nfce_disabler.disable_fiscal_number(eTree.XML(order_xml))
                custom_properties = {
                    "ORDER_DISABLED": "true",
                    "DISABLED_FISCAL_XML": base64.b64encode(xml),
                }
                self.order_service.set_custom_properties(
                    pos_id=pos_id,
                    order_id=order_key.order_id,
                    custom_properties=custom_properties,
                )
                logger.info("Order inutilizada com sucesso: {0}".format(order_key.order_id))
            except RequestException:
                logger.exception("Erro de Conexao com a Sefaz tentando inutulizar nota, tentaremos novamente...")
            except OrderTakerException:
                logger.exception("Order Taker Error, tentaremos novamente...")
            except (Exception,):
                message = "Erro inutilizando nota, verifique o Layout e os parametros enviados pela Sefaz, "\
                    "não tentaremos novamente."
                logger.exception(message)
                self.order_service.set_custom_property(
                    pos_id=pos_id,
                    order_id=order_key.order_id,
                    key="ORDER_DISABLED",
                    value="false",
                )
            finally:
                time.sleep(5)
