from odoo import models, fields, api
from odoo.exceptions import UserError, ValidationError,Warning
from psycopg2 import sql, DatabaseError

from werkzeug import utils


class EventType(models.Model):
    _inherit = "event.type"
    _description = 'Event Template'
    
    booking_event = fields.Boolean(string="Booking event", tracking=True)
    booking_option_ids=fields.One2many('booking.option','event_type_id','booking options')
    booking_questionnaire_id=fields.Many2one(
        'booking.questionnaire',
		String='Questionnaire',
        index=True,
        track_visibility='onchange',
        ondelete='cascade'
    )
class EventBookingOptions(models.Model):
    _name='booking.option'
    _description='booking options for events'
    booking_option_id=fields.Many2one('product.product',string='booking options',domain="['|',('booking_option_product','=','True'),('booking_option_product_backoffice','=','True')]")
    name=fields.Char(related='booking_option_id.name')
    
    booking_option_price=fields.Monetary('Price',currency_field='currency_id')
    booking_option_member_price=fields.Monetary('Member price',currency_field='currency_id')
    booking_option_super_member_price=fields.Monetary('Super member price',currency_field='currency_id')
    
    event_type_id = fields.Many2one(
        'event.type',
		String='Event type',
        index=True,
        readonly=True,
        track_visibility='onchange',
        ondelete='cascade'
    )
    event_id = fields.Many2one(
        'event.event',
		String='Event',
        index=True,
        readonly=True,
        track_visibility='onchange',
        ondelete='cascade'
    )


    @api.model
    def _default_currency(self):
        company = self.env['res.company']._company_default_get(
            'event.event')
        return company.currency_id
   
    currency_id = fields.Many2one(
        'res.currency',
        string='Currency',
        required=True,
        track_visibility='onchange',
        ondelete='restrict',
        default=_default_currency
    )
    @api.onchange('booking_option_id')
    def onchange_booking_option(self):
    
        #for option in self:
        if self.booking_option_id:
            bo= self.env['product.product'].search([('id',"=",int(self.booking_option_id))])
            
            self.booking_option_price= bo.lst_price
    
    


    

class BookingEvent(models.Model):
    _inherit = "event.event"
    _description = 'Event'
    individual_booking_event=fields.Boolean(string="individual booking event", tracking=True)
    questionnaire_id=fields.Many2one('booking.questionnaire','questionnaire')
    question_ids=fields.One2many(
        'event.question',
        'event_id',
        string='Questions'
        
    )
    
    

    @api.onchange('questionnaire_id')
    def onchange_questionnaire(self):

        #on supprime les question existantes:
        self.question_ids=False
        questions=self.env['booking.question'].search([('questionnaire_id','=',int(self.questionnaire_id))])
        
        #on rappatrie les questions
        for question in questions:
            
            vals={}
            vals['event_id']=self.id
            vals['sequence']=question.sequence
            vals['question']=question.question
            self.question_ids = [(0, 0, vals)]

        
    
    def csv_booking_registrants(self):
        act={ 'type': 'ir.actions.act_url',
        'url': '/event/csv_booking_registrants?id=%s' % (self.id),
         'target': 'self','res_id': self.id}
        return act
    def generate_csv_booking_registrants(self,id):
        booking=self.env['event.event'].search([('id','=',int(id))])
        
        header_ligne='Nom & Prénom;Genre;Rôle;Options;Montant retraite;Adhésion;Autre options;Montant à payer;Statut commande;Type de paiement;Règlement\n'
        if booking.booking_event:
            header_ligne='Date de début;Nom & Prénom;Genre;Rôle;Options;Montant retraite;Adhésion;Autre options;Montant à payer;Statut commande;Type de paiement;Règlement\n'

        csv_lines=''
        for reg in booking.registration_ids:
            if reg.state in ('draft','cancel'): continue
            name=str(reg.name)
            if reg.firstname:name=name+' '+str(reg.firstname)
            if reg.gender=='male':gender='homme'
            elif reg.gender=='femelle':gender='femme'
            else:gender='N/A'
            role=self._compute_member_status(reg)
            if role=='not member':role='non adhérent'
            elif role=='member':role='adhérent'
            elif role=='super member':role='membre de soutien'
            else: role='N/A'

            options=self._compute_invoice_options(reg)
            booking_amount=str(round(self._compute_booking_amount(reg)))
            membership_amount=str(round(self._compute_membership_amount(reg)))
            invoice_options_amount= str(round(self._compute_invoice_options_amount(reg)))
            amount_to_be_paid=str(round(self._compute_amount_to_be_paid(reg)))
            payment_status=str(reg.payment_status)
            payment_mode=self._compute_payment_mode(reg)
            amount_paid=str(round(self._compute_amount_paid(reg)))
            start_date=str(reg.start_day_individual_booking)

            if booking.individual_booking_event:
                csv_lines=csv_lines+start_date+';'+name+';'+gender+';'+role+';'+options+';'+booking_amount+';'+membership_amount+';'+invoice_options_amount+';'+amount_to_be_paid+';'+payment_status+';'+payment_mode+';'+amount_paid+'\n'
            else:
                csv_lines=csv_lines+name+';'+gender+';'+role+';'+options+';'+booking_amount+';'+membership_amount+';'+invoice_options_amount+';'+amount_to_be_paid+';'+payment_status+';'+payment_mode+';'+amount_paid+'\n'
        
        return str.encode(header_ligne+csv_lines,'utf-8')
    
    def _compute_payment_mode(self,rec):
        
            payment_mode=''
            if rec.invoice_id:
                payment_mode=rec.invoice_id.payment_mode_id.name
            if rec.down_payment_invoice_id:
                payment_mode=rec.down_payment_invoice_id.payment_mode_id.name
            return payment_mode

    def _compute_amount_paid(self,rec):
        
            amount_paid=0
            if rec.invoice_id:
                amount_paid=rec.invoice_id.amount_total-rec.invoice_id.amount_residual
            if rec.down_payment_invoice_id:
                amount_paid=amount_paid+rec.down_payment_invoice_id.amount_total-rec.down_payment_invoice_id.amount_residual
            if rec.balance_invoice_id:
                amount_paid=amount_paid+rec.balance_invoice_id.amount_total-rec.balance_invoice_id.amount_residual
            if rec.end_of_stay_invoice_id:
                amount_paid=amount_paid+rec.end_of_stay_invoice_id.amount_total-rec.end_of_stay_invoice_id.amount_residual
            
            return amount_paid
    def _compute_amount_to_be_paid(self,rec):
        
            amount_to_be_paid=0
            if rec.invoice_id:
                amount_to_be_paid=rec.invoice_id.amount_residual
            if rec.down_payment_invoice_id:
                amount_to_be_paid=amount_to_be_paid+rec.down_payment_invoice_id.amount_residual
            if rec.balance_invoice_id:
                amount_to_be_paid=amount_to_be_paid+rec.balance_invoice_id.amount_residual
            if rec.end_of_stay_invoice_id:
                amount_to_be_paid=amount_to_be_paid+rec.end_of_stay_invoice_id.amount_residual
            return amount_to_be_paid
    def _compute_invoice_options_amount(self,rec):
            membership_product=self.env['product.product'].sudo().search([('membership_product','=',True)],limit=1)
        
            invoice_options_amount=0
            #si facture sans acompte:
            i=1
            
            if rec.invoice_id:
                
                for line in rec.invoice_id.invoice_line_ids:
                    if i>1:
                        if line.name!=membership_product.name:                        
                            invoice_options_amount=invoice_options_amount+line.price_subtotal
                    i=i+1
            #si facture avec acompte:
            i=1
            
            if rec.balance_invoice_id:
                
                for line in rec.balance_invoice_id.invoice_line_ids:
                    if i>1:
                        if line.name!=membership_product.name:
                            invoice_options_amount=invoice_options_amount+line.price_subtotal
                    i=i+1
            i=1
            if rec.end_of_stay_invoice_id:
                for line in rec.end_of_stay_invoice_id.invoice_line_ids:
                    if i>1:
                        if line.name!=membership_product.name:
                            invoice_options_amount=invoice_options_amount+line.price_subtotal
                        
                    i=i+1
            return invoice_options_amount

    def _compute_booking_amount(self,rec):
            membership_product=self.env['product.product'].sudo().search([('membership_product','=',True)],limit=1)
        
            #si facture sans acompte:
            booking_amount=0
            i=1
            if rec.invoice_id:
                for line in rec.invoice_id.invoice_line_ids:
                        booking_amount=line.price_subtotal
                        break
                        
                   
            #si facture avec acompte:
                       
            if rec.down_payment_invoice_id:
                
                for line in rec.down_payment_invoice_id.invoice_line_ids:
                    if line.name!=membership_product.name:
                        booking_amount=line.price_subtotal
                        break
                for line in rec.balance_invoice_id.invoice_line_ids:
                    if line.name!=membership_product.name:
                        booking_amount=booking_amount+line.price_subtotal
                        break

            return booking_amount

    def _compute_member_status(self,reg):
        
            if reg.partner_id.email==reg.email:
                status=reg.partner_id.member_status
            #le participant n'est pas la personne qui s'est connecté
            
            else:
                participant=self.env['res.partner'].sudo().search([('email','=',reg.email)],limit=1)
                if participant:
                    status=participant.member_status
                else:
                    status='not member'        
            return str(status)
    
    def _compute_membership_amount(self,rec):
            membership_product=self.env['product.product'].sudo().search([('membership_product','=',True)],limit=1)
        
            #si facture sans acompte:
            membership_amount=0
            
            if rec.invoice_id:
                for line in rec.invoice_id.invoice_line_ids:
                   if line.name==membership_product.name:
                        membership_amount=line.price_subtotal
                        
                   
            #si facture avec acompte:
                       
            if rec.balance_invoice_id:
                for line in rec.balance_invoice_id.invoice_line_ids:
                    if line.name==membership_product.name:
                        membership_amount=line.price_subtotal
                        
            return membership_amount     

    
    def _compute_invoice_options(self,rec):
            membership_product=self.env['product.product'].sudo().search([('membership_product','=',True)],limit=1)
        
            invoice_options=''
           
            #si facture sans acompte:
            i=1
            
            if rec.invoice_id:
                for line in rec.invoice_id.invoice_line_ids:
                    if i>1:
                        if line.name!=membership_product.name:
                            invoice_options=invoice_options+str(line.name)+'('+str(line.price_subtotal)+' €)- '
                        
                    i=i+1
            #si facture avec acompte:
            i=1
            
            if rec.balance_invoice_id:
                for line in rec.balance_invoice_id.invoice_line_ids:
                    if i>1:
                        if line.name!=membership_product.name:
                            invoice_options=invoice_options+str(line.name)+'('+str(line.price_subtotal)+' €)- '
                        
                    i=i+1
            i=1
            if rec.end_of_stay_invoice_id:
                for line in rec.end_of_stay_invoice_id.invoice_line_ids:
                    if i>1:
                        if line.name!=membership_product.name:
                            invoice_options=invoice_options+str(line.name)+'('+str(line.price_subtotal)+' €)- '
                        
                    i=i+1
            return str(invoice_options)
    # booking_option_ids=fields.One2many('booking.option','event_id','booking options')
    
    # @api.model
    # def _default_currency(self):
    #     company = self.env['res.company']._company_default_get(
    #         'event.event')
    #     return company.currency_id

    # currency_id = fields.Many2one(
    #     'res.currency',
    #     string='Currency',
    #     required=True,
    #     states={'done': [('readonly', True)]},
    #     track_visibility='onchange',
    #     ondelete='restrict',
    #     default=_default_currency
    #)
    # booking_price=fields.Monetary('Price',currency_field='currency_id')
    # booking_member_price=fields.Monetary('Member price',currency_field='currency_id')
    # booking_super_member_price=fields.Monetary('Super member price',currency_field='currency_id')
    # booking_down_payment=fields.Monetary('Down payment',currency_field='currency_id')
    # booking_product_id=fields.Many2one('product.product',string='booking product',domain="[('booking_product','=','True')]")
    

    # @api.depends('event_type_id')
    # def _compute_booking_event(self):
    #     self.booking_event=self.event_type_id.booking_event
        
    # @api.onchange('event_type_id')
    # def onchange_state(self):
    #     self.booking_event=self.event_type_id.booking_event
        
    #     booking_option=self.env['booking.option'].search([('event_type_id','=',int(self.event_type_id))])
    #     if booking_option:
    #         on supprime les options existantes:
    #         self.booking_option_ids=False

    #         on rappatrie les options du modèle
    #         for option in booking_option:
    #             vals={}
    #             vals['event_id']=self.id
    #             vals['booking_option_id']=option.booking_option_id
    #             vals['booking_option_price']=option.booking_option_price
    #             vals['currency_id']=option.currency_id
    #             self.booking_option_ids = [(0, 0, vals)]
        
        
    #     if self.event_type_id.booking_questionnaire_id:
            
    #         on supprime les question existantes:
    #         self.question_ids=False
    #         questions=self.env['booking.question'].search([('questionnaire_id','=',int(self.event_type_id.booking_questionnaire_id))])
    #         on rappatrie les question
    #         for question in questions:
    #             vals={}
    #             vals['event_id']=self.id
    #             vals['sequence']=question.sequence
    #             vals['question']=question.question
                
    #             self.question_ids = [(0, 0, vals)]

        #super(event, self).write(vals)
        #self.booking_option_ids=self.event_type_id.booking_option_ids
class event_question(models.Model):
    _name = 'event.question'
    _description = 'event question'
    
    question=fields.Text(string='question')
    sequence = fields.Integer(string="sequence", default=10)
    event_id = fields.Many2one(
        'event.event',
		String='Questionnaire',
        index=True,
        readonly=True,
        track_visibility='onchange',
        ondelete='cascade'
    )

class event_partner_category(models.Model):
    _name = 'event.partner_category'
    _description = 'map partner categories vs member or super-member for pricing'
    
    partner_category_id=fields.Many2one(
        'res.partner.category',
        String='Category',
        index=True,
        track_visibility='onchange',
        ondelete='cascade'
    )
    
    status=fields.Selection(selection=[('member','Member'),('supermember','Super Member')])

class event_membership_product(models.Model):
    _name = 'event.membership_product'
    _description = 'membership product'

    membership_product_id=fields.Many2one('product.product',string='Membership product',domain="[('booking_option_product','=','True')]")

class event_email_manager(models.Model):
    _name = 'event.email.manager'
    _description = 'e-mails of individuals retreats managers to inform'
    
    name=fields.Char('name')
    firstname=fields.Char('firstname')
    email=fields.Char(string='e-mail')
    event_id = fields.Many2one(
        'event.event',
		String='event',
        index=True,
        readonly=True,
        track_visibility='onchange',
        ondelete='restrict'
    )
