# -*- coding: utf-8 -*-

import pytz

from odoo import _, api, fields, models
from odoo.addons.mail.models.mail_template import format_tz
from odoo.exceptions import AccessError, UserError, ValidationError
from odoo.tools.translate import html_translate
import uuid
from datetime import datetime

class AVTVoucher(models.Model):
    _name = "etourism.avt.voucher"
    _description = "Voucher"

    name = fields.Char('Code Voucher', readonly=True)
    owner_id = fields.Many2one('etourism.enterprise', 'Agency', required=True, ondelete='restrict')
    agency_id = fields.Many2one('etourism.enterprise', 'Agency', required=True, ondelete='restrict')
    type = fields.Selection(
        [('0', 'Percentage'), ('1', 'Fixed Value')],
        'Type', required=True, default='0')
    value = fields.Float('Value')
    state = fields.Selection(
        [('active', 'Active'), ('not_active', 'Not Active')],
        'State', required=True, default='active')
    usage = fields.Boolean('Restrict Usage?',default=True)
    voucher_used = fields.Boolean('Voucher Used?')
    order_ids = fields.One2many('etourism.avt.voucher.order', 'voucher_id', 'Orders', copy=False)
    price_item_id = fields.Many2one('product.pricelist.item', 'Price Item')
    expire_date = fields.Datetime('Expire Date')
    remaining_amount = fields.Float(compute="compute_remaining_voucher_discount", string="Remaining Discount", readonly=True)

    _sql_constraints = [('uniq_name', 'unique(name)', 'Code must be unique for each Voucher.')]

    def validate(self):

        if self.usage and self.voucher_used:
            return {'valid':False,'message': 'Restricted usage only'}
        elif self.expire_date and  datetime.strptime(self.expire_date, '%Y-%m-%d %H:%M:%S') < datetime.now():
            return {'valid': False, 'message': 'Voucher Expired'}

        return {'valid': True}

    @api.model
    def default_get(self, fields):
        res = super(AVTVoucher, self).default_get(fields)
        if self.env.uid:
            enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
            if enterprise_id:
                res.update({'owner_id': enterprise_id.id})
        return res

    @api.onchange('type','value')
    def onchange_type_value(self):
        if self.type and self.type==0 and self.value and ( self.value<0 or self.value>100):
            raise ValidationError('Percentage values must be between 0 and 100')


    @api.one
    def action_close(self):
        self.state = 'not_active'

    @api.model
    def create(self, vals):
        """Generate voucher code
        """
        context = self._context
        random = str(uuid.uuid4()) # Convert UUID format to a Python string.
        random = random.upper() # Make all characters uppercase.
        random = random.replace("-","") # Remove the UUID '-'.
        vals['name'] = random[0:8]

        if 'expire_date' in vals and vals['expire_date']  and datetime.strptime(vals['expire_date'], '%Y-%m-%d %H:%M:%S') < datetime.now():
            raise ValidationError('You cannot set a expire date before now.')

        return super(AVTVoucher, self).create(vals)

    @api.depends('type', 'usage', 'order_ids')
    def compute_remaining_voucher_discount(self):
        amount, paid = 0, 0
        for voucher in self:
            if voucher.type == '1' and voucher.usage is True:
                total = voucher.value
                for order in voucher.order_ids:
                    paid += order.amount
                amount = total - paid
            voucher.remaining_amount = amount

class AVTVoucherOrder(models.Model):
    _name = "etourism.avt.voucher.order"
    _description = "Voucher Orders"

    voucher_id = fields.Many2one('etourism.avt.voucher', 'Voucher')
    order_id = fields.Many2one('sale.order', 'Sales Order')
    date = fields.Date('Date')
    amount = fields.Float('Voucher Discount')
