from datetime import datetime
from typing import Optional

from staff.person.models import Organization as StaffOrganization

from staff.oebs import exceptions
from staff.oebs import constants
from staff.oebs.models import Organization

OEBS_DATETIME_FORMAT = '%Y/%m/%d %H:%M:%S'


def status(active_status):
    return {value: key for key, value in constants.ACTIVE_STATUS}.get(active_status, 1)


def organization_id(oebs_org_id: Optional[int]) -> Optional[int]:
    if oebs_org_id is None:
        return StaffOrganization.get_outstaff_org().id

    try:
        organization = Organization.objects.get(org_id=oebs_org_id)
        return organization.dis_organization_id
    except Organization.DoesNotExist as dne:
        raise exceptions.ObjectNotFound(
            dne,
            'Organization[org_id=%s] not found' % oebs_org_id,
        )


def guid(person_guid):
    return person_guid.replace('-', '').lower()


def datetime_from_string(datetime_as_string):
    if datetime_as_string == '':
        return None
    return datetime.strptime(datetime_as_string, OEBS_DATETIME_FORMAT)


def yes_no(yesno_str):
    return {
        'да': True,
        'ДА': True,
        'yes': True,
        'y': True,
    }.get(yesno_str.lower(), False)
