import requests

from trytond.pool import Pool
from trytond.model import ModelView, fields
from trytond.wizard import Wizard, StateView, Button, StateTransition
from trytond.transaction import Transaction


# 'Content-type': 'application/json',
HEADERS = {
   'Accept': '*/*',
   'Authorization': None
}

URL_GUEST = 'https://pms.mincit.gov.co/one/'

URL_OTHERS = 'https://pms.mincit.gov.co/two/'

TYPE_DOC = {
    '11': 'R.C.',  # REGISTRO CIVIL
    '12': 'T.I.',  # TARGETA IDENTIDAD
    '13': 'C.C.',  # CEDULA
    '22': 'C.E.',  # CEDULA EXTRANJERIA
    '41': 'Pasaporte',  # PASAPORTE
    '47': 'P.E.',  # PERMISO ESPECIAL
}

SEX = {
    'male': 'M',
    'female': 'F',
}

# "fecha_nacimiento": str(guest.birthday or ''),
# "genero": SEX[guest.sex],
# "nacionalidad": country,
# "ocupacion": "",
# "pais_residencia": country,
# "departamento_residencia": subdivision,
# "pais_procedencia": country,
# "departamento_procedencia": subdivision,

# "nit_establecimiento": company.party.id_number,
# "lugar_nacimiento": nationality,
# "fecha_nacimiento": str(guest.birthday or ''),
# "genero": SEX[guest.sex],
# "nacionalidad": nationality,
# "n_habitaciones": rooms,
# "ocupacion": "Ninguna",
# "pais_residencia": country,
# "departamento_residencia": subdivision,
# "pais_procedencia": country,
# "departamento_procedencia": subdivision,
# "medio_reserva": "Ninguno",


def send_siat(company, guest, folio, token):
    HEADERS['Authorization'] = 'token ' + token
    city = guest.city.rec_name if guest.city else ''
    # subdivision = guest.subdivision.rec_name if guest.subdivision else ''
    # nationality = guest.nationality.rec_name if guest.nationality else ''
    # country = guest.country.rec_name if guest.country else ""
    first_name = guest.first_name or ''
    second_name = guest.second_name or ''
    first_family_name = guest.first_family_name or ''
    second_family_name = guest.second_family_name or ''
    if not first_name or not first_family_name:
        return
    num_acom = len(folio.guests) - 1
    if num_acom <= 0:
        num_acom = 0
    guest = {
        "tipo_identificacion": TYPE_DOC[guest.type_document],
        "numero_identificacion": guest.id_number,
        "nombres": first_name + ' ' + second_name,
        "apellidos": first_family_name + ' ' + second_family_name,
        "cuidad_residencia": city,
        "cuidad_procedencia": city,
        "numero_habitacion": folio.room.code,
        "motivo": "Turismo",
        "numero_acompanantes": str(num_acom),
        "check_in": str(folio.arrival_date),
        "check_out": str(folio.departure_date),
        "tipo_acomodacion": folio.product.name,
        "costo": str(int(folio.total_amount)),
        "nombre_establecimiento": company.party.name,
        "rnt_establecimiento": company.rnt_code,
    }

    res = requests.post(URL_GUEST, data=guest, headers=HEADERS)

    guests = []
    res = res.json()
    for guest in folio.guests:
        if folio.main_guest:
            continue

        first_name = guest.first_name or ''
        second_name = guest.second_name or ''
        first_family_name = guest.first_family_name or ''
        second_family_name = guest.second_family_name or ''
        # country = guest.country.rec_name if guest.country else ""
        guests = {
            "tipo_identificacion": TYPE_DOC[guest.type_document],
            "numero_identificacion": guest.id_number,
            "nombres": first_name + ' ' + second_name,
            "apellidos": first_family_name + ' ' + second_family_name,
            "cuidad_residencia": city,
            "cuidad_procedencia": city,
            "numero_habitacion": folio.room.code,
            "check_in": str(folio.arrival_date),
            "check_out": str(folio.departure_date),
            "padre": res['code'],
        }
        requests.post(URL_OTHERS, data=guests, headers=HEADERS)
    return res


class SiatSyncStart(ModelView):
    'Siat Sync Start'
    __name__ = 'hotel.siat_sync.start'
    company = fields.Many2One('company.company', 'Company', required=True)
    start_date = fields.Date('Start Date', required=True)
    end_date = fields.Date('End Date', required=True)

    @staticmethod
    def default_company():
        return Transaction().context.get('company')


class SiatSyncWizard(Wizard):
    'Siat Sync Wizard'
    __name__ = 'hotel.siat_sync.wizard'
    start = StateView(
        'hotel.siat_sync.start',
        'hotel.siat_sync_start_view_form', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Ok', 'accept', 'tryton-ok'),
        ]
    )
    accept = StateTransition()

    def transition_accept(self):
        pool = Pool()
        Folio = pool.get('hotel.folio')
        folios = Folio.search([
            ('booking.company', '=', self.start.company),
            ('guests.siat_send_date', '=', None),
            ('arrival_date', '>=', self.start.start_date),
            ('departure_date', '<=', self.start.end_date),
        ])
        for folio in folios:
            folio.sync_send_siat()
        return 'end'
