from typing import Optional

from pydantic import BaseModel, Field, root_validator

from ...logic.registrar.password import get_registrar_decrypted_password


class RegistrarOutSchema(BaseModel):
    id: int
    pdd_id: Optional[int]
    pdd_version: Optional[str]
    password: str
    name: str
    admin_id: int
    oauth_client_id: Optional[str]
    validate_domain_url: Optional[str]
    domain_added_callback_url: Optional[str]
    domain_verified_callback_url: Optional[str]
    domain_deleted_callback_url: Optional[str]

    payed_url: Optional[str] = Field(..., alias='validate_domain_url')
    added_init: Optional[str] = Field(..., alias='domain_added_callback_url')
    added: Optional[str] = Field(..., alias='domain_verified_callback_url')
    delete_url: Optional[str] = Field(..., alias='domain_deleted_callback_url')

    class Config:
        orm_mode = True

    @root_validator(pre=True)
    def decrypt_password(cls, values):
        values = dict(values)
        values['password'] = get_registrar_decrypted_password(
            password=values['password'],
            pdd_version=values['pdd_version'],
            iv=values['iv'],
            plength=values['plength'],
        )
        return values


class RegistrarTokenOutSchema(BaseModel):
    token: str

    class Config:
        orm_mode = True


class RegistrarByTokenOutSchema(BaseModel):
    id: int
    pdd_id: Optional[int]
    admin_id: int

    class Config:
        orm_mode = True


class RegistrarUpdateSchema(BaseModel):
    pdd_id: Optional[int]
    pdd_version: Optional[str]
    name: Optional[str]
    admin_id: Optional[str]
    password: Optional[str]
    oauth_client_id: Optional[str]
    validate_domain_url: Optional[str] = Field(..., alias='payed_url')
    domain_added_callback_url: Optional[str] = Field(..., alias='added_init')
    domain_verified_callback_url: Optional[str] = Field(..., alias='added')
    domain_deleted_callback_url: Optional[str] = Field(..., alias='delete_url')

    class Config:
        allow_population_by_field_name = True
