from typing import Dict, Optional, Union

from posot import OrderTaker, OrderTakerException
from sysactions import StopAction

from actions.models.mw_sys_errors import MwSysErrors


def create_order(
    pos_ot,             # type: OrderTaker
    pos_id,             # type: Union[int, str]
    price_list,         # type: str
    multi_order_id="",  # type: Optional[str]
    order_type="SALE",  # type: Optional[str]
    sale_type="",       # type: Optional[str]
    order_sub_type="",  # type: Optional[str]
):
    # type: (...) -> Dict

    try:
        return pos_ot.createOrder(
            posid=int(pos_id),
            pricelist=price_list,
            saletype=sale_type,
            multiorderid=multi_order_id,
            orderType=order_type,
            orderSubType=order_sub_type,
        )
    except OrderTakerException as ex:
        error_code_message, error_message = ex.message.split(";")
        error_code = error_code_message.split(":")[-1].strip()
        if error_code == MwSysErrors.SE_ORDER_IS_ALREADY_OPENED.value:
            raise StopAction()
        raise
