import json
from datetime import datetime

from sysactions import action
from typing import (
    Any,
    Dict,
    List,
    Union,
)

from .. import mb_context
from application.interactor import SectorOperatorInteractor


ALL_SECTORS = "$ALL_SECTORS"
SECTORS = []
OPERATORS_BY_SECTORS = {}


def get_sectors(
    pos_id,     # type: Any[Union[int, str]]
):
    # type: (...) -> List[str]

    global SECTORS
    if SECTORS:
        return SECTORS

    from msgbusboundary import MsgBusTableService as tableService

    sector_operator_interactor = SectorOperatorInteractor(table_service=tableService())
    sectors = sector_operator_interactor.get_sectors(pos_id=pos_id)
    SECTORS = json.loads(sectors or "[]")
    if ALL_SECTORS not in SECTORS:
        SECTORS.insert(0, ALL_SECTORS)

    return SECTORS


def get_operator_sector_info(
    pos_id,     # type: Any[Union[int, str]]
):
    # type: (...) -> Dict[str, List[int]]

    global OPERATORS_BY_SECTORS
    if OPERATORS_BY_SECTORS:
        return OPERATORS_BY_SECTORS

    from msgbusboundary import MsgBusTableService as tableService

    sector_operator_interactor = SectorOperatorInteractor(table_service=tableService())
    operators_by_sectors = sector_operator_interactor.get_operator_sector_info(pos_id=pos_id)
    OPERATORS_BY_SECTORS = json.loads(operators_by_sectors or "{}")

    return OPERATORS_BY_SECTORS


@action
def get_operator_sector_info_front(
    pos_id,     # type: str
):
    # type: (...) -> str

    operator_sector_info = get_operator_sector_info(pos_id=pos_id)
    operator_sector_info = json.dumps(operator_sector_info)

    return operator_sector_info


@action
def update_operator_sector_info(
    pos_id,         # type: Any[Union[int, str]]
    update_info,    # type: Dict
):
    # type: (...) -> None

    global OPERATORS_BY_SECTORS

    from msgbusboundary import MsgBusTableService as tableService

    sector_operator_interactor = SectorOperatorInteractor(table_service=tableService())
    updated_operator_sector_info = sector_operator_interactor.update_operator_sector_info(
        pos_id=pos_id,
        update_info=update_info,
    )
    OPERATORS_BY_SECTORS = json.loads(updated_operator_sector_info or "{}")

    mb_context.MB_EasyEvtSend(
        subject="SECTOR_INFO_MODIFIED",
        type="",
        xml=str(datetime.now())
    )
