import json

import cfgtools
from typing import List

from ._PickupArea import PickupArea
from ._PickupAreaSector import PickupAreaSector


def get_first_of(it, default_value=None):
    return next(it, default_value)


class PickupConfig(object):
    def __init__(
        self,           # type: PickupConfig
        pickup_config,  # type: cfgtools.Group
    ):
        # type: (...) -> None

        self.pickup_areas = []
        self.parse_pickup_config(pickup_config=pickup_config)

    def parse_pickup_config(
        self,
        pickup_config,
    ):
        # type: (...) -> None

        for area in pickup_config.groups:
            name = get_first_of(x for x in area.keys if x.name == "PickupName").values[0]
            sectors = get_first_of(x for x in area.keys if x.name == "Sectors").values

            self.pickup_areas.append(
                PickupArea(
                    pickup_name=name,
                    sectors=self._get_sectors(sectors),
                )
            )

    @staticmethod
    def _get_sectors(
        sectors,        # type: List[str]
    ):
        # type: (...) -> List[PickupAreaSector]

        current_sectors = []
        for sector in sectors:
            sector_dict = json.loads(sector)
            pickup_area_sector = PickupAreaSector(
                name=sector_dict.get("name", ""),
                excluded_pos=sector_dict.get("excludedPOS", []),
            )
            current_sectors.append(pickup_area_sector)

        return current_sectors
