from odoo import api, fields, models


class SubProject(models.Model):
    _inherit = "project.project"
    # _description = "Sub Project"

    is_sub_project = fields.Boolean("Is Sub Project")
    sub_project = fields.Many2many('project.project', 'project_subproject_rel', 'project_id', 'id',
                                   domain="[('is_sub_project', '=', True),('parent_project', '=', False)]", string='Sub Project')
    parent_project = fields.Many2one('project.project', domain="[('is_sub_project', '=', False)]", string='Parent Project')
    total_timesheet_time_sub_project = fields.Integer(compute='_compute_total_timesheet_time_sub_project')

    def _compute_total_timesheet_time_sub_project(self):
        for project in self:
            total_time = 0.0
            record = self.env['account.analytic.line'].search([(('sub_project', '=', project.id))])
            for timesheet in record:
                total_time += timesheet.unit_amount * timesheet.product_uom_id.factor_inv
            total_time *= project.timesheet_encode_uom_id.factor
            project.total_timesheet_time_sub_project = total_time
            #project.total_timesheet_time_sub_project = int(round(total_time))


    def action_view_custom_sub_project(self):
        action = self.env["ir.actions.actions"]._for_xml_id("hr_timesheet.timesheet_action_all")
        action['domain'] = [('sub_project', '=', self.id)]
        action['context'] = {'search_default_sub_project': self.id}
        return action

    # @api.onchange('parent_project', 'sub_project')
    # def onchange_parent_project_sub_project(self):
    #     if self.parent_project.sub_project:
    #         if self.parent_project:
    #             user_list = self.parent_project.sub_project.ids
    #             print('11111111111', self, self.id, self._origin.id)
    #             user_list.append(self._origin.id)
    #             self.parent_project.sub_project = user_list
    #         else:
    #             self.parent_project.sub_project = self.ids
    #     if self.sub_project:
    #         for rec in self.sub_project:
    #             sub_project = self.env['project.project'].search([('id', '=', rec._origin.id)], limit=1)
    #             sub_project.write({'parent_project': self._origin.id})

    @api.model
    def create(self, vals):
        value = super(SubProject, self).create(vals)
        if value and value.parent_project:
            if value.parent_project.sub_project:
                user_list = value.parent_project.sub_project.ids
                user_list.append(value.id)
                value.parent_project.sub_project = user_list
            else:
                value.parent_project.sub_project = value.ids
        if value and value.sub_project:
            value.write({'parent_project': value.id})
        return value

    def write(self, vals):
        list1 = self.sub_project.ids
        res = super(SubProject, self).write(vals)
        if vals.get('parent_project'):
            parent_prjt = self.env['project.project'].search([('id', '=', vals.get('parent_project'))], limit=1)
            user_list = parent_prjt.sub_project.ids
            user_list.append(self.id)
            parent_prjt.sub_project = user_list
        if vals.get('sub_project'):
            list2 = self.sub_project.ids
            if len(list2) > len(list1):
                list3 = (set(list2)) - (set(list1))
                for record in list(list3):
                    self.env['project.project'].search([('id', '=', int(record))], limit=1).write(
                        {'parent_project': self.id})
            if len(list1) > len(list2):
                list3 = (set(list1)) - (set(list2))
                for record in list(list3):
                    self.env['project.project'].search([('id', '=', int(record))], limit=1).write(
                        {'parent_project': False, 'is_sub_project': False})

        return res


class InheritProjectTask(models.Model):
    _inherit = 'project.task'

    sub_project = fields.Many2many('project.project', related='project_id.sub_project', string='Sub Project')
