# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.exceptions import ValidationError


class ProjectCreateExpense(models.TransientModel):
    _name = 'project.create.expense'
    _description = "Create Expense from project"

    @api.model
    def default_get(self, fields):
        result = super(ProjectCreateExpense, self).default_get(fields)
        active_model = self._context.get('active_model')
        if active_model != 'project.project':
            raise UserError(_('You can only apply this action from a project.'))
        active_id = self._context.get('active_id')
        if 'project_id' in fields and active_id:
            result['project_id'] = active_id
        if 'analytic_id' in fields and active_id:
            project = self.env['project.project'].browse(active_id)
            if not project.analytic_account_id:
                raise UserError(_("Please define Analytic Account."))
            result['analytic_id'] = project.analytic_account_id.id
        return result

    project_id = fields.Many2one('project.project', "Project", required=True)
    analytic_id = fields.Many2one('account.analytic.account', "Analytic Account", required=True)
    description = fields.Char(string="Description", required=True)
    ispercentage = fields.Boolean(string="Is Percentage", default=False)
    #sale_order_id = fields.Many2one('sale.order', string="Sales Order", domain="['|', '|', ('partner_id', '=', partner_id), ('partner_id', 'child_of', commercial_partner_id), ('partner_id', 'parent_of', partner_id)]")
    expenses_from = fields.Selection([
        ('invoiced', 'Invoiced'),
        ('to_invoice', 'To Invoice')
    ], "Expenses from", default='to_invoice')
    per_from_amt = fields.Float(string="Of", digits=(6, 2))
    percentage_rate = fields.Float(string="Percentage (%)")
    expenses_amt = fields.Float(string="Amount", digits=(6, 2), required=True)

    @api.onchange('ispercentage', 'expenses_from')
    def onchange_ispercentage(self):
        active_id = self._context.get('active_id')
        if self.ispercentage and self.expenses_from:
            profit = dict.fromkeys(['invoiced', 'to_invoice'], 0.0)
            profitability_raw_data = self.env['project.profitability.report'].read_group([('project_id', '=', active_id)],
                ['project_id', 'amount_untaxed_to_invoice', 'amount_untaxed_invoiced'], ['project_id'])
            for data in profitability_raw_data:
                profit['invoiced'] += data.get('amount_untaxed_invoiced', 0.0)
                profit['to_invoice'] += data.get('amount_untaxed_to_invoice', 0.0)
            if self.expenses_from == 'invoiced':
                self.per_from_amt =  profit['invoiced']
            if self.expenses_from == 'to_invoice':
                self.per_from_amt = profit['to_invoice']
            #if self.percentage_rate > 0.0 and self.per_from_amt > 0.0:
                #expense_amount =  self.per_from_amt * (self.percentage_rate / 100)
            #self.expenses_amt = expense_amount

    @api.onchange('ispercentage', 'per_from_amt', 'percentage_rate')
    def onchange_percentage_rate(self):
        if self.percentage_rate > 0.0 and self.per_from_amt > 0.0:
            expense_amount = self.per_from_amt * (self.percentage_rate / 100)
            self.expenses_amt = expense_amount


    def action_create_project_expense(self):
        expenses_amt = self.expenses_amt
        if expenses_amt == 0:
            raise ValidationError(_("Amount shoud not be zero"))
        if expenses_amt > 0:
            expenses_amt = expenses_amt * -1
        analytic = self.env['account.analytic.line'].create({
            'project_id': False,
            'partner_id': False,
            'account_id': self.project_id.analytic_account_id.id,
            'name': self.description,
            'date': fields.Date.context_today(self),
            'user_id': self.env.uid,
            'product_uom_id': False,
            #'amount': self.expenses_amt * -1,
            'amount': expenses_amt
        })
        action = self.env["ir.actions.actions"]._for_xml_id("analytic.account_analytic_line_action")
        action['context'] = {'default_account_id': self.analytic_id.id}
        action['domain'] = [('account_id', '=', self.analytic_id.id)]
        return action


