from odoo import models, fields, api
from odoo.exceptions import UserError, ValidationError, Warning
from psycopg2 import sql, DatabaseError
from datetime import date,datetime,timedelta
from dateutil.relativedelta import relativedelta
import logging
from werkzeug import utils
import re
_logger = logging.getLogger(__name__)
import json

class AccountMove(models.Model):
    _inherit = 'account.move'

    description=fields.Char(compute='_compute_description')
    transaction_date=fields.Datetime(compute='_compute_transaction_date')
    transaction_amount=fields.Float(compute='_compute_transaction_amount')
    systempay_ref=fields.Text(compute='_compute_systempay_ref')
    date_compta=fields.Datetime('date import',default=False)
    date_compta_end_of_stay=fields.Datetime('date import',default=False)
    date_compta_out_refund=fields.Datetime('date import',default=False)
    out_invoice_id=fields.Many2one('account.move' ,ondelete="cascade",domain="[('partner_id','=',partner_id),('move_type','=','out_invoice'),('state','!=','paid')]")
    payment_ids=fields.Many2many('account.payment',compute='_compute_payment_ids')
    down_payment_paid=fields.Boolean(compute='_compute_down_payment_paid')
    is_balance_invoice=fields.Boolean(compute='_compute_is_balance_invoice')
    def write(self, data):

        
        res = super(AccountMove, self).write(data)
        membership=False
        #Si option d'adhesion on prepare la creation de l'adhesion
        membership_product=self.env['product.product'].sudo().search([('membership_product','=',True)],limit=1)
        for line in self.invoice_line_ids:
            if membership_product.id==int(line.product_id.id):
                 membership=True
                 break
            
        
       
        if self.payment_state=='paid'  and membership:
             #recherche de l'ahésion associée à la facture
             m=self.env['kalachakra.membership'].search([('invoice_id','=',int(self.id))])
             if m:
                  m.start_date=datetime.now()
                  m.end_date=datetime.now()+relativedelta(years=1)
                  #m.email_confirmation()
                  
                  #mise à jour des dates adhésions à partir de la date de paiement
             else:
                  #création de l'adhésion
                vals={}
                vals['invoice_id']=int(self.id)
                vals['partner_id']=int(self.partner_id)
                vals['product_id']=int(membership_product.id)
                vals['start_date']=datetime.now()
                vals['end_date']=datetime.now()+relativedelta(years=1)
                vals['amount']=line.price_unit
                vals['state']='done'
                membership=self.env['kalachakra.membership'].sudo().create(vals)
             
        
        return True
         
    def _compute_payment_ids(self):
        
        payments=self.env['account.payment'].sudo().search([])
        
        for rec in self:
            rec.payment_ids=False
            for p in payments:
                for recon in p.reconciled_invoice_ids:
                    if recon.id==rec.id:
                            rec.write({'payment_ids':[(4,p.id)]})
        
           
                               

    def _compute_description(self):
        
        for a in self:
            
            a.description=''
            for line in a.line_ids:
                    a.description=line.product_id.name
                    break
    
    def _compute_transaction_date(self):
        
        for a in self:
            a.transaction_date=False
            for t in a.transaction_ids:
                    a.transaction_date=t.date
                    break

    def _compute_transaction_amount(self):
        
        for a in self:
            a.transaction_amount=False
            for t in a.transaction_ids:
                    a.transaction_amount=t.amount
                    break

    def _compute_systempay_ref(self):
        
        for a in self:
            a.systempay_ref=False
            for t in a.transaction_ids:
                    if t.systempay_raw_data:
                        raw=t.systempay_raw_data.split(",")
                        for r in raw:
                            r_s=r.split(":")
                            #_logger.error('vads:'+r_s[0])
                            if r_s[0]==" 'vads_order_id'":
                                a.systempay_ref=r_s[1].replace("'","")
                    break
    
    def _compute_down_payment_paid(self):
        reg=self.env['event.registration'].search([('balance_invoice_id','=',self.id)])
         
        if reg :
             if reg.date_payment_down_payment :self.down_payment_paid=True
             else :self.down_payment_paid=False

        else:
         self.down_payment_paid=False


         down_payment_paid=True
    
    def _compute_is_balance_invoice(self):
         reg=self.env['event.registration'].search([('balance_invoice_id','=',self.id)])
         if reg:self.is_balance_invoice=True
         else:self.is_balance_invoice=False
         
    def button_event_registration(self):
         reg=self.env['event.registration'].search(['|','|','|',('invoice_id','=',self.id),\
                                                    ('down_payment_invoice_id','=',self.id),\
                                                    ('balance_invoice_id','=',self.id),\
                                                    ('end_of_stay_invoice_id','=',self.id)])
         
         if reg :
              event_id=reg.event_id
              action=self.env.ref('event.action_registration').read()[0]

              action.update({
                'view_mode': 'form',
                'res_id': reg.id,
                'view_type':'form',
                "views": [[False, "form"]],
               
                
            })
              return action
                
