import json
import logging

from msgbus import (
    FM_PARAM,
    MBException,
    TK_SYS_ACK,
)
from sysactions import send_message
from model.customexception import (
    ComponentNotFound,
    ErrorGettingSalesChallenge,
    ErrorOnInsertSalesChallenge,
    ErrorOnDeleteSalesChallenge,
    ErrorOnUpdateSalesChallenge,
)
from bustoken import TK_DAILY_GOALS_GET_SALES_CHALLENGE, TK_DAILY_GOALS_INSERT_SALES_CHALLENGE,\
    TK_DAILY_GOALS_DELETE_SALES_CHALLENGE, TK_DAILY_GOALS_UPDATE_SALES_CHALLENGE


class DailyGoalsInteractor(object):
    def __init__(self):
        # type: () -> None
        self.logger = logging.getLogger("PosActions")

    @staticmethod
    def get_sales_challenge(pos_id, quantity):
        # type: (int, int) -> json

        data = json.dumps(dict(posId=pos_id, quantity=quantity))

        try:
            response = send_message(
                dest_name="DailyGoals",
                token=TK_DAILY_GOALS_GET_SALES_CHALLENGE,
                format=FM_PARAM,
                data=data,
                timeout=30000000,
            )
            if response.token == TK_SYS_ACK:
                return json.loads(response.data)

            raise ErrorGettingSalesChallenge(response.data)

        except MBException as ex:
            if "SE_NOTFOUND" in ex.message:
                raise ComponentNotFound("DailyGoals")

            raise ErrorGettingSalesChallenge(ex)

    @staticmethod
    def insert_sales_challenge(sale_challenge):
        # type: (dict) -> bool

        data = json.dumps(sale_challenge)

        response = send_message("DailyGoals", TK_DAILY_GOALS_INSERT_SALES_CHALLENGE, FM_PARAM, data, timeout=30000000)
        if response.token == TK_SYS_ACK:
            return True

        raise ErrorOnInsertSalesChallenge(response.data)

    @staticmethod
    def update_sales_challenge(sale_challenge):
        # type: (dict) -> bool

        data = json.dumps(sale_challenge)

        response = send_message("DailyGoals", TK_DAILY_GOALS_UPDATE_SALES_CHALLENGE, FM_PARAM, data, timeout=30000000)
        if response.token == TK_SYS_ACK and response.data == '1':
            return True

        raise ErrorOnUpdateSalesChallenge(response.data)

    @staticmethod
    def remove_sales_challenge(sale_challenge_id):
        # type: (int) -> json

        data = json.dumps(dict(sale_challenge_id=sale_challenge_id))

        response = send_message("DailyGoals", TK_DAILY_GOALS_DELETE_SALES_CHALLENGE, FM_PARAM, data, timeout=30000000)
        if response.token == TK_SYS_ACK and response.data == '1':
            return json.loads(response.data)

        raise ErrorOnDeleteSalesChallenge(response.data)
