# -*- coding: utf-8 -*-
import json

from sysactions import (
    action,
    show_messagebox,
)

from .. import logger
from operator_by_sector import (
    update_operator_sector_info,
    get_sectors,
)

ALL_SECTORS = "$ALL_SECTORS"


@action
def save_sector_operators(
    pos_id,                 # type: str
    available_operators,    # type: str
    selected_operators,     # type: str
    selected_sector,        # type: str
):
    # type: (...) -> None

    try:
        if not selected_sector:
            raise

        available_operators_list = json.loads(available_operators)
        selected_operators_list = json.loads(selected_operators)

        if selected_sector != ALL_SECTORS:
            insert_sector_operators = [[selected_sector, s.get("id")] for s in selected_operators_list]
            delete_sector_operators = [[selected_sector, s.get("id")] for s in available_operators_list]
        else:
            insert_sector_operators = []
            delete_sector_operators = []
            all_sectors = get_sectors(pos_id=pos_id)
            for sector in all_sectors:
                if sector == ALL_SECTORS:
                    continue
                insert_sector_operators.extend([[sector, s.get("id")] for s in selected_operators_list])
                delete_sector_operators.extend([[sector, s.get("id")] for s in available_operators_list])

        update_info = dict(
            delete=delete_sector_operators,
            insert=insert_sector_operators,
        )
        update_operator_sector_info(
            pos_id=pos_id,
            update_info=update_info,
        )

        show_messagebox(
            posid=pos_id,
            message="$OPERATORS_BY_SECTOR_UPDATE_SUCCESS",
        )
    except Exception as e:
        logger.exception('[save_sector_operators] Exception {}'.format(e))
        show_messagebox(
            posid=pos_id,
            message="$ERROR_SAVING_OPERATORS_BY_SECTOR",
            buttons="$EXIT",
        )
