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

import logging

from application.repository import OrderRepository
from actions import mb_context
from sysactions import get_poslist, translate_message, get_model
from typing import List, Optional


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)

    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 []
