from odoo import models, fields, api
from dateutil.relativedelta import relativedelta
from datetime import datetime

class kalachakra_membership(models.Model):
    _name = 'kalachakra.membership'
    _description = 'manage membership'

    
    partner_id = fields.Many2one(
        'res.partner',
        string='partner',
        required=True,
        index=True,
        track_visibility='onchange',
        ondelete='restrict'
    )
    product_id=fields.Many2one('product.product',required=True,string='membership product',domain="[('membership_product','=',True)]")
    start_date=fields.Date('start date',required=True,default=lambda self: fields.Date.today())
    invoice_id=fields.Many2one('account.move','invoice')
    payment_state=fields.Selection(string='payment_state',selection=[('paid', 'paid'), ('not paid', 'not paid')],compute='_compute_payment_state')
    
    def _compute_payment_state(self):
        for rec in self:
            rec.payment_state='not paid'
            #adhesion via page d'ahésion
            if rec.state=='done':rec.payment_state='paid'
            #adhésion via isncription à l'événement
            if rec.invoice_id:
                if rec.invoice_id.payment_state=='paid':
                    rec.payment_state='paid'
                    rec.state='done'

    def _default_end_date(self):
        
        return datetime.now()+relativedelta(years=1)

    end_date=fields.Date('end date',required=True,default=_default_end_date)
    state=fields.Selection(string='state',selection=[('draft', 'draft'), ('done', 'done')],default='draft')
    currency_id = fields.Many2one(
        "res.currency",
        string="Currency",
        required=True,
        tracking=True,
        ondelete="restrict",
        default=lambda self: self.env.company.currency_id,
    )
   

    amount = fields.Monetary(
        string="Amount",
        currency_field="currency_id",
        tracking=True,
        
    )
    
    @api.onchange('product_id')
    def onchange_product_id(self):
        if self.product_id:
            self.amount = self.product_id.list_price

    def _get_payment_type(self, tokenize=False):
        self.ensure_one()
        return 'form_save' if tokenize else 'form'

    def _create_payment_transaction(self, vals):
        '''Similar to self.env['payment.transaction'].create(vals) but the values are filled with the
        current membership fields (e.g. the partner or the currency).
        :param vals: The values to create a new payment.transaction.
        :return: The newly created payment.transaction record.
        '''
        # Ensure the currencies are the same.
        currency = self[0].currency_id
        # if any(so.pricelist_id.currency_id != currency for so in self):
        #     raise ValidationError(_('A transaction can\'t be linked to sales orders having different currencies.'))

        # Ensure the partner are the same.
        partner = self[0].partner_id
        if any(so.partner_id != partner for so in self):
            raise ValidationError(_('A transaction can\'t be linked to sales orders having different partners.'))

        # Try to retrieve the acquirer. However, fallback to the token's acquirer.
        acquirer_id = vals.get('acquirer_id')
        acquirer = False
        payment_token_id = vals.get('payment_token_id')

        if payment_token_id:
            payment_token = self.env['payment.token'].sudo().browse(payment_token_id)

            # Check payment_token/acquirer matching or take the acquirer from token
            if acquirer_id:
                acquirer = self.env['payment.acquirer'].browse(acquirer_id)
                if payment_token and payment_token.acquirer_id != acquirer:
                    raise ValidationError(_('Invalid token found! Token acquirer %s != %s') % (
                    payment_token.acquirer_id.name, acquirer.name))
                if payment_token and payment_token.partner_id != partner:
                    raise ValidationError(_('Invalid token found! Token partner %s != %s') % (
                    payment_token.partner.name, partner.name))
            else:
                acquirer = payment_token.acquirer_id

        # Check an acquirer is there.
        if not acquirer_id and not acquirer:
            raise ValidationError(_('A payment acquirer is required to create a transaction.'))

        if not acquirer:
            acquirer = self.env['payment.acquirer'].browse(acquirer_id)

        # Check a journal is set on acquirer.
        if not acquirer.journal_id:
            raise ValidationError(_('A journal must be specified for the acquirer %s.', acquirer.name))

        if not acquirer_id and acquirer:
            vals['acquirer_id'] = acquirer.id

        vals.update({
            'amount': sum(self.mapped('amount')),
            'currency_id': currency.id,
            'partner_id': partner.id,
            'membership_ids': [(6, 0, self.ids)],
            'type': self[0]._get_payment_type(vals.get('type')=='form_save'),
        })

        transaction = self.env['payment.transaction'].create(vals)

        # Process directly if payment_token
        if transaction.payment_token_id:
            transaction.s2s_do_transaction()

        return transaction
    
    # @api.model
    # def create(self,vals):

    #     res=super(kalachakra_membership, self).create(vals)
                
    #     #on ajoute l'étiquette membre au contact
    #     #si l'étiquette membre n'existe pas on l'a créé !
    #     label_member=self.env['res.partner.category'].search([('name','=','member')])
    #     id_label_member=label_member.id
    #     if not label_member:
    #         vals={}
    #         vals['name']='member'
    #         res=self.env['res.partner.category'].create(vals)
    #         id_label_member=res.id
    #     partner=self.env['res.partner'].search([('id','=',int(self.partner_id))])
    #     if partner:
    #         if id_label_member not in partner.category_id:
    #             partner.write({category_id:(4, id_label_member)})
            


