import json

from msgbus import TK_SLCTRL_OMGR_DOSALE, FM_PARAM, TK_SYS_NAK, TK_SYS_ACK
from posot import OrderTakerException
from systools import sys_log_info


class OrderTaker(object):
    def __init__(self, pos_ot, mb_context):
        self.pos_ot = pos_ot
        self.mb_context = mb_context

    def do_sale(self, pos_id, item_id, price_list, qty=1, verify_option=True, sale_type='', after_total='0',
                apply_default_options=False, custom_properties=None):
        custom_properties = custom_properties if custom_properties else {}
        params = ('1' if self.pos_ot.blkopnotify else '0',
                  int(pos_id),
                  item_id,
                  price_list,
                  qty,
                  '1' if verify_option else '0',
                  '',
                  self.pos_ot.originatorId,
                  self.pos_ot.originatorNumber,
                  self.pos_ot.businessPeriod,
                  self.pos_ot.podType,
                  self.pos_ot.sessionId,
                  self.pos_ot.additionalInfo,
                  sale_type,
                  after_total,
                  '1' if apply_default_options else '0',
                  json.dumps(custom_properties))

        sys_log_info('POSOT do_sale: {0}'.format(params))
        req_buf = '\x00'.join((str(p) for p in params))
        msg = self.mb_context.MB_EasySendMessage('ORDERMGR%s' % pos_id, TK_SLCTRL_OMGR_DOSALE, FM_PARAM, req_buf)
        params = msg.data.split('\x00')
        if msg.token == TK_SYS_NAK:
            raise OrderTakerException(params[0], params[1])
        if msg.token == TK_SYS_ACK and len(params) > 2:
            return params[2]

        return ''
