import uuid
from uuid import UUID
import logging
from datetime import date

import attr

from staff.budget_position import const
from staff.budget_position.workflow_service import entities
from staff.budget_position.workflow_service.use_cases.push_workflow_to_oebs import PushWorkflowToOebs

logger = logging.getLogger(__name__)


class CreateWorkflowForMaternity:
    def __init__(
        self,
        repository: entities.WorkflowRepositoryInterface,
        budget_position_repository: entities.BudgetPositionsRepository,
        oebs_service: entities.OEBSService,
        push_usecase: PushWorkflowToOebs,
    ):
        self._repository = repository
        self._budget_position_repository = budget_position_repository
        self._oebs_service = oebs_service
        self._push_usecase = push_usecase

    def create(self, data: entities.service_dtos.MoveToMaternityData) -> UUID:
        new_position = self._get_change_for_new_position(data)
        workflow = entities.workflows.MaternityWorkflow(uuid.uuid1(), [new_position])
        workflow.confirm()
        logger.info('Created workflow %s with id %s', workflow.code, workflow.id)

        workflow_id = self._repository.save(workflow)
        self._push_usecase.push(workflow_id, data.responsible_id)
        return workflow_id

    def _get_change_for_new_position(self, data: entities.service_dtos.MoveToMaternityData) -> entities.Change:
        logger.info('Getting existing budget position properties')
        existing_bp_info = self._oebs_service.get_position_as_change(data.budget_position)
        existing_bp_info.department_id = data.department_id  # TODO: доставать департамент из БП

        crossing_info = self._oebs_service.get_crossing_position_info_as_change(data.budget_position, data.login)

        if crossing_info:
            existing_bp_info = attr.evolve(
                existing_bp_info,
                grade_id=crossing_info.grade_id,
                currency=crossing_info.currency,
                rate=crossing_info.rate,
            )

        new_position_change = attr.evolve(
            existing_bp_info,
            effective_date=date.today().isoformat(),
            budget_position=None,
            position_name='Декрет',
            position_type=const.PositionType.MATERNITY,
            salary=0,
            ticket=data.ticket,
        )
        return new_position_change
