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

from odoo import api, fields, models, tools


class BudgetHrsAnalysis(models.Model):

    _name = "project.consultant.hrs.report"
    _description = "Project consultant hours analysis report"
    _rec_name = "project_id"
    #_order = 'project_id desc, hours_type asc, end_date desc, employee_id'
    _auto = False

    project_id = fields.Many2one('project.project', string='Project', 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)
    hours_type = fields.Char(string="Hours Type", readonly=True)
    hours = fields.Float("Hours", digits=(16, 2), readonly=True, group_operator="sum")
    percentage = fields.Float("Percentage (%)")
    #roworder =  fields.Integer("Row Order")
    #ptime = fields.Char(string="Time", readonly=True)

    @api.depends('project_id', 'employee_id')
    def name_get(self):
        res = []
        for record in self:
            name = record.project_id and record.project_id.name or ''
            if record.employee_id.name:
                name = record.employee_id.name + '/' + name + '/' + record.hours_type
            res.append((record.id, name))
        return res

    """def _generate_order_by(self, order_spec, query):
        order_by = super(BudgetHrsAnalysis, self)._generate_order_by(order_spec, query)
        print("order by>>>>>>>>>>>>>>", order_by)
        return order_by"""

    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, start_date, end_date, employee_id,  hours_type, hours, percentage
        from (
        select project_id as project_id, start_date as start_date, end_date as end_date,
         employee_id as employee_id, 'Budgeted Hours for period' as hours_type, budgeted_hours as hours,
        percentage as percentage
        from project_consultant_hrs ph
        union
        select project_id as project_id, start_date as start_date, end_date as end_date,
         employee_id as employee_id, 'Actual Hours for period' as hours_type, actual_hours as hours,
        actual_percentage as percentage
        from project_consultant_hrs ph
        ) as res order by
              project_id desc,
              hours_type,
              employee_id, end_date, start_date
        )""" % (self._table,))


