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

from odoo import fields, models, tools


class ProjectConsultantCustomReport(models.Model):

    _name = "project.consultant.custom.report"
    _description = "Project Consultant Custom Analysis report"
    #_order = 'project_id'
    _auto = False

    project_id = fields.Many2one('project.project', string='Project', readonly=True)
    parent_project = fields.Many2one('project.project', string='Parent Project', readonly=True)
    partner_id = fields.Many2one('res.partner', string='Client', readonly=True)
    employee_id = fields.Many2one('hr.employee', string='Consultant', readonly=True)
    start_date = fields.Date(string='Start Date', readonly=True)
    end_date = fields.Date(string='End Date', readonly=True)
    percentage = fields.Float("Budgeted Percentage (%)")
    budgeted_hours = fields.Float("Budgeted Hours for period", compute='_compute_budgeted_hours', store=True)
    actual_percentage = fields.Float("Actual Percentage (%)", compute='_compute_actual_calc', store=True)
    actual_hours = fields.Float("Actual Hours for period", compute='_compute_actual_calc', store=True)

    def init(self):
        '''Create the view'''
        tools.drop_view_if_exists(self._cr, self._table)
        self._cr.execute("""
        CREATE OR REPLACE VIEW %s AS (
            SELECT ROW_NUMBER() OVER() as id, 
            project_id, 
            parentproject as parent_project, 
            employee_id,
            partner_id,
            start_date,
            end_date,
            percentage,
            budgeted_hours,
            actual_percentage,
            actual_hours 
            from (
                select pro.id AS project_id,
                (select project_id from project_subproject_rel as par where pro.id=par.id limit 1) as parentproject,
                pro.partner_id AS partner_id,
                consult.employee_id AS employee_id,
                consult.start_date as start_date,
                consult.end_date as end_date,
                consult.percentage percentage,
                consult.budgeted_hours AS budgeted_hours,
                consult.percentage AS actual_percentage,
                consult.actual_percentage AS actual_hours
                FROM project_project PRO
                right JOIN project_consultant_hrs consult ON PRO.id = consult.project_id
                WHERE PRO.active = 't' and PRO.pricing_type='employee_rate' and PRO.project_type='hours_in_consultant'  
                ) res
        )""" % (self._table,))


