# This file is part of Tryton.  The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.

from trytond.pool import PoolMeta, Pool
from trytond.model import fields
from trytond.wizard import Wizard, StateView, Button, StateTransition
from trytond.transaction import Transaction
from trytond.exceptions import UserError
from trytond.i18n import gettext


class Party(metaclass=PoolMeta):
    __name__ = 'party.party'
    '''
    Party field and function aditions for channels management.  Sales
    commissions, taxes and price lists.
    '''
    visa_category = fields.Char('Visa Category')
    visa_number = fields.Char('Visa Number')
    visa_date = fields.Date('Visa Date')
    subdivision = fields.Function(fields.Many2One('party.department_code',
        'Subdivision'), 'get_subdivision')
    city = fields.Function(fields.Many2One('party.city_code', 'City'),
        'get_city')
    address = fields.Function(fields.Char('Address'), 'get_address')
    country = fields.Function(fields.Many2One('party.country_code',
        'Country'), 'get_country')

    @classmethod
    def create(cls, vlist):
        for value in vlist:
            if value.get('address'):
                address = value.pop('address')
                country = value.pop('country', None)
                to_create = {
                    'street': address,
                }
                if country:
                    to_create['country_code'] = country

                value['addresses'] = [
                    ('create', [to_create])
                ]
            if value.get('email'):
                val = value.pop('email')
                value['contact_mechanisms'] = [
                    ('create', [{
                        'type': 'email', 'value': val
                    }])
                ]
            if value.get('mobile'):
                val = value.pop('mobile')
                value['contact_mechanisms'] = [
                    ('create', [{
                        'type': 'mobile', 'value': val
                    }])
                ]
        return super().create(vlist)

    @classmethod
    def write(cls, records, values):
        email = None
        mobile = None
        street = None
        pool = Pool()
        country = None
        Address = pool.get('party.address')
        CM = pool.get('party.contact_mechanism')
        if values.get('email'):
            email = values.pop('email')
        if values.get('mobile'):
            mobile = values.pop('mobile')
        if values.get('address'):
            street = values.pop('address')
        if values.get('country'):
            country = values.pop('country')

        for rec in records:
            if street:
                if rec.addresses:
                    address = rec.addresses[0]
                    address.street = street
                    address.save()
                else:
                    new_add = {
                        "party": rec.id,
                        "street": street,
                        "country_code": country,
                    }
                    Address.create([new_add])

            for mc in rec.contact_mechanisms:
                if mc.type == 'email' and email:
                    mc.value = email
                    mc.save()
                    email = None
                if mc.type == 'mobile' and mobile:
                    mc.value = mobile
                    mc.save()
                    mobile = None

            if mobile:
                CM.create([{
                    "party": rec.id, "type": "mobile", "value": mobile
                }])
            if email:
                CM.create([{
                    "party": rec.id, "type": "email", "value": email
                }])
        return super().write(records, values)

    def get_subdivision(self, name=None):
        for address in self.addresses:
            if address.department_code:
                return address.department_code.id

    def get_address(self, name=None):
        if self.addresses:
            return self.addresses[0].street

    def get_city(self, name=None):
        for address in self.addresses:
            if address.city_code:
                return address.city_code.id

    def get_country(self, name=None):
        for address in self.addresses:
            if address.country_code:
                return address.country_code.id


class CreateGuest(Wizard):
    'Create Party to Guest'
    __name__ = 'hotel.party.guest'
    start = StateView(
        'party.party',
        'hotel.view_party_guest', [
            Button('Exit', 'end', 'tryton-cancel'),
            Button('Create', 'create_', 'tryton-ok', default=True),
        ]
    )
    create_ = StateTransition()

    def transition_create_(self):
        pool = Pool()
        Party = pool.get('party.party')
        Booking = pool.get('hotel.booking')
        id = Transaction().context.get('active_id', False)
        record = Booking(id)
        parties = Party.search([
            ('id_number', '=', self.start.id_number)
        ])
        if parties:
            raise UserError(gettext('El usuario ya existe!'))
        else:
            contact_mechanisms = []
            for contact in self.start.contact_mechanisms:
                contact_mechanisms.append({
                    'type': contact.type, 'value': contact.value
                })

            if self.start.type_document == '31':
                type_person = 'persona_juridica'
            else:
                type_person = 'persona_natural'

            to_create = {
                'name': self.start.name,
                'id_number': self.start.id_number,
                'type_document': self.start.type_document,
                'type_person': type_person,
                'birthday': self.start.birthday,
                'sex': self.start.sex,
                'first_name': self.start.first_name,
                'second_name': self.start.second_name,
                'first_family_name': self.start.first_family_name,
                'second_family_name': self.start.second_family_name,
                'contact_mechanisms': [('create', contact_mechanisms)],
                'addresses': [('create', [{
                    'street': '',
                }])]
            }
            party, = Party.create([to_create])
            party_id = party.id
            Booking.write([record], {'party': party_id})
            if record.lines:
                for folio in record.lines:
                    if not folio.main_guest:
                        folio.main_guest = party_id
                        folio.save()
        return 'end'
