# -*- coding: utf-8 -*-

import logging

from msgbus import (
    TK_SLCTRL_OMGR_CLEARTENDERS,
    FM_PARAM,
    TK_SYS_ACK
)
from posot import OrderTakerException

from application.repository import OrderRepository
from actions import mb_context
from sysactions import (
    translate_message,
    get_model, send_message
)
from typing import (
    List,
    Optional, Tuple
)


class OrderInteractor(object):
    def __init__(self, pos_id):
        # type: (str) -> None

        self.logger = logging.getLogger("PosActions")
        self.order_repository = OrderRepository(mb_context)
        self.model = get_model(pos_id)
        self.pos_id = pos_id

    def get_orders_benefit(self, initial_date, end_date, operator_id):
        # type: (str, str, Optional[str]) -> List

        from msgbusboundary import MsgBusTableService as tableService
        try:
            all_coupons = translate_message(self.model, "ALL_COUPONS")
            pos_list = sorted(tableService().get_exclusive_pos_list())
            result = {'All': {'index': 0, 'id': None, 'name': all_coupons}}
            benefits = self.order_repository.get_orders_benefit(initial_date, end_date, operator_id, pos_list)
            index = 1
            for benefit in benefits:
                benefit_detail = benefit["benefit"]
                benefit_id = benefit_detail.get("id")
                if benefit_id in result.keys():
                    continue
                name = benefit_detail.get("userDescription").encode('utf-8')
                key = benefit_detail.get("name").encode('utf-8')
                data = {'index': index, 'id': benefit_id, 'name': name, 'key': key}
                result[benefit_id] = data
                index += 1

            return sorted(result.values(), key=lambda k: k['index'])
        except Exception as _:
            self.logger.exception("Error getting orders benefit")
            return []

    def clear_order_tender(
        self,
        order_tender_id,            # type: str
        order_id,                   # type: str
        blk_notify="0",             # type: str
        tender_id="",               # type: str
        keep_tender_records="0",    # type: str
    ):
        # type: (...) -> None

        params = (
            blk_notify,
            self.pos_id,
            tender_id,
            order_tender_id,
            keep_tender_records,
            order_id
        )
        self.send_order_message(params, TK_SLCTRL_OMGR_CLEARTENDERS)

    def send_order_message(
        self,
        params,     # type: Tuple
        token       # type: int
    ):
        params = "\0".join(str(p) for p in params)

        msg = send_message(
            "ORDERMGR%d" % int(self.pos_id),
            token,
            FM_PARAM,
            params,
            timeout=1000000 * 120
        )

        if msg.token != TK_SYS_ACK:
            params = msg.data.split('\0')
            self.logger.error("Error clear order tender: {} - {} - {}", params[0], params[0], params[1])

        return msg.data
