import datetime

from pydantic import BaseModel, validator
from typing import Optional

from intranet.trip.src.enums import (
    Citizenship,
    DocumentType,
    Gender,
)


DOCUMENT_TYPE_MAPPING = {
    'national': DocumentType.passport,
    'international': DocumentType.external_passport,
}


class Contact(BaseModel):
    id: str = ''
    first_name: Optional[str] = ''
    second_name: Optional[str]
    last_name: Optional[str] = ''
    email: str = ''
    phone_number: str = ''
    owner_service: Optional[str] = 'tools_trip'


class DocumentBase(BaseModel):
    id: str = ''
    user_id: str
    user_type: str
    doc_number: str
    doc_type: DocumentType  # тип: national, international
    create_time: datetime.datetime = None
    modification_time: datetime.datetime = None
    last_used_time: datetime.datetime = None
    version: str = None
    verification_data: str = None
    verification_status: str = None
    issued_for_user: str = None
    self_doc: bool = True
    default: bool = False

    @validator('doc_type', pre=True, always=True)
    def set_doc_type(cls, v):
        return DOCUMENT_TYPE_MAPPING.get(v, DocumentType.other)

    @validator('create_time', 'modification_time', 'last_used_time', pre=True, always=True)
    def set_datetime(cls, v):
        return datetime.datetime.strptime(v, '%Y-%m-%dT%H:%M:%S%z')


class NationalPassport(DocumentBase):
    passport_types: str = 'national'
    first_name: str
    last_name: str
    middle_name: str = None
    birth_place: str
    birth_date: datetime.date
    country: Citizenship
    gender: Gender
    # issue document
    issue_date: datetime.date = None
    issued_by: str = None
    issuer_subdivision_code: str = None
    # registration fields
    registration_region: str = None
    registration_org: str = None
    registration_org_code: str = None
    registration_date: datetime.date = None
    registration_locality: str = None
    registration_street: str = None
    registration_house: str = None
    registration_housing: str = None
    registration_apartment: str = None

    @validator('country', pre=True, always=True)
    def set_country(cls, v):
        if v.upper() == 'RU':
            return Citizenship.RU
        return Citizenship.OTHER

    @validator('birth_date', 'issue_date', 'registration_date', pre=True, always=True)
    def set_birthday(cls, v):
        return datetime.datetime.strptime(v, '%d.%m.%Y').date()


# FIXME: after passport will be released
class InternationalPassport(DocumentBase):
    passport_types: str = 'international'


Document = NationalPassport | InternationalPassport
