import logging
from typing import Any, Dict, Iterable

from staff.oebs.constants import PERSON_POSITION_STATUS
from staff.oebs.controllers.datasources.json_datasource import JsonDatasource


logger = logging.getLogger(__name__)


class OebsHeadcountPositionsDatasource(JsonDatasource):
    def get_iter(self, data: Dict[str, Any]) -> Iterable[Dict[str, Any]]:
        for department_data in data['detOrgLimits']:
            department_id = department_data['global_org_id']

            if department_id <= 0:
                logger.info('Skipping global_org_id %s from OEBS', department_id)
                continue

            for state in department_data.get('states', []):
                for position in state['positions']:
                    status = state['state1']

                    if status not in dict(PERSON_POSITION_STATUS):
                        logger.info('Skipping state1 %s from OEBS', status)
                        continue

                    yield self._parse_position(position, state, department_data)

    @classmethod
    def _parse_position(
        cls,
        position: Dict[str, Any],
        state: Dict[str, Any],
        department_data: Dict[str, Any]
    ) -> Dict[str, Any]:
        position_code = position['code']
        assignment_id = position.get('assignmentID')

        return {
            'id': f'{position_code}_{assignment_id}',
            'code': position_code,
            'name': position['name'],

            'status': state['state1'],
            'state2': state['state2'],
            'relevance_date': cls.get_date(department_data['relevanceDate']),

            'headcount': position['hc'],
            'main_assignment': bool(position.get('asgFlag', True)),
            'is_total_hc': position.get('isTotalHc'),

            'department_id': department_data['global_org_id'],
            'hr_product_id': position['productID'],
            'geography_oebs_code': position['geo'],

            'bonus_id': position['rwsBonusID'],
            'reward_id': position['rwsRewardID'],
            'review_id': position['rwsReviewID'],

            'current_login': position['loginCurr'],
            'previous_login': position['loginPrev'],
            'assignment_index': position.get('indx', 1),
            'prev_assignment_index': position.get('prevIndx'),
            'next_assignment_index': position.get('nextIndx'),
            'assignment_id': assignment_id,
            'batch_id': position.get('batchId'),
        }
