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

from odoo import fields, models, tools, api
from datetime import datetime, time, timedelta
from odoo.tools.float_utils import float_round

class ProjectTimesheetReport(models.Model):

    _name = "project.timesheet.report"
    _description = "Project Timesheet Report"
    #_order = 'start_date desc, duration, project_id desc'
    _order = 'start_datetime desc, end_datetime asc'
    _auto = False

    start_date = fields.Date(string='Start Date', readonly=True)
    start_time = fields.Char(string='Start Time', readonly=True)
    end_time = fields.Char(string='End Time', readonly=True)
    start_datetime = fields.Datetime("Start DateTime", required=True)
    end_datetime = fields.Datetime("End DateTime", required=True)
    employee_id = fields.Many2one('hr.employee', string='Employee', readonly=True)
    project_id = fields.Many2one('project.project', string='Project', readonly=True)
    sub_project = fields.Many2one('project.project', string='Sub Project', readonly=True)
    duration = fields.Float('Duration', readonly=True)
    timestamp = fields.Char('Timestamp', readonly=True)
    task_id = fields.Many2one('project.task', string='Task', readonly=True)
    description = fields.Char('Description', readonly=True)
    active = fields.Boolean(string="Active", readonly=True)
    #sub_project = fields.Many2many('project.project', compute='_compute_related_subproject')

    """@api.depends('project_id')
    def _compute_related_subproject(self):
        for val in self:
            val.sub_project = val.project_id.sub_project.ids"""

    @api.model
    def search_read(self, domain=None, fields=None, offset=0,limit=None, order=None):
        if order and isinstance(order, str) and order=='timestamp ASC':
            #order = order.replace("timestamp ", "start_datetime ")
            order = "start_datetime asc, end_datetime asc"
        if order and isinstance(order, str) and order=='timestamp DESC':
            #order = order.replace("timestamp ", "start_datetime ")
            order = "start_datetime desc, end_datetime asc"
        res = super(ProjectTimesheetReport, self).search_read(domain, fields, offset, limit, order)
        return res

    @api.model
    def export_data(self, fields):
        index = range(len(fields))
        fields_name = dict(zip(fields, index))
        res = super(ProjectTimesheetReport, self).export_data(fields)
        for index, val in enumerate(res['datas']):
            """if fields_name.get('start_date') is not None:
                tdateindex = fields_name.get('start_date')
                tdate = res['datas'][index][tdateindex]
                if tdate:
                    res['datas'][index][tdateindex] = datetime.strftime(tdate, "%d/%m/%Y")"""
            if fields_name.get('task_id') is not None:
                taskindex = fields_name.get('task_id')
                ttask = res['datas'][index][taskindex]
                if type(ttask) == bool:
                    res['datas'][index][taskindex] = ''
            if fields_name.get('project_id') is not None:
                projectindex = fields_name.get('project_id')
                project = res['datas'][index][projectindex]
                if type(project) == bool:
                    res['datas'][index][projectindex] = ''
            if fields_name.get('sub_project') is not None:
                subindex = fields_name.get('sub_project')
                subproject = res['datas'][index][subindex]
                if type(subproject) == bool:
                    res['datas'][index][subindex] = ''
            if fields_name.get('duration') is not None:
                durationindex = fields_name.get('duration')
                duration =  res['datas'][index][durationindex] and float(res['datas'][index][durationindex])
                if duration:
                    duration_time = round(duration, 2)
                    res['datas'][index][durationindex] = duration_time
                    #duration_time = tools.format_duration(duration)
                    #res['datas'][index][durationindex] = duration_time
        return res

    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,
         aal.start_datetime::date as start_date,
         to_char(start_datetime at time zone 'utc' at time zone 'Asia/Jerusalem', 'HH24:MI') as start_time,
         to_char(end_datetime at time zone 'utc' at time zone 'Asia/Jerusalem', 'HH24:MI') as end_time,
         aal.start_datetime as start_datetime,
         aal.end_datetime as end_datetime,
         aal.employee_id,
         aal.project_id,
         aal.sub_project,
         unit_amount as duration,
         CONCAT(to_char((start_datetime at time zone 'utc') at time zone 'Asia/Jerusalem',  'HH24:MI'), '-',
                        to_char((end_datetime at time zone 'utc') at time zone 'Asia/Jerusalem', 'HH24:MI')) as timestamp,
         --CONCAT(to_char(start_datetime at time zone 'utc', 'HH24:MI'), '-', to_char(end_datetime at time zone 'utc', 'HH24:MI')) as timestamp,
         task_id,
         aal.name as description,
         pro.active as active
         from account_analytic_line aal
         left join project_project pro on pro.id = aal.project_id
         --left join hr_employee emp on emp.id = aal.employee_id
         --where pro.active = True
        )""" % (self._table,))


