# -*- coding: utf-8 -*-
# Powered by Kanak Infosystems LLP.
# © 2020 Kanak Infosystems LLP. (<https://www.kanakinfosystems.com>).

import datetime

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


class CompanyResourceCalendar(models.Model):
    _name = 'company.resource.calendar'
    _description = 'Company Resouce Calendar'
    _inherit = ['mail.thread']

    def _compute_selection(self):
        flag = 0
        year_list = []
        year = datetime.datetime.now().year
        while flag <= 10:
            year_list.append((str(year), str(year)))
            flag += 1
            year += 1
        return year_list

    name = fields.Char('Name', required=1)
    company_global_leave_ids = fields.One2many(
        'company.resource.calendar.leaves', 'company_calendar_id', string='Company Global Leaves')
    employee_id = fields.Many2one('hr.employee', string='Employee')
    year = fields.Datetime()
    year_list = fields.Selection(selection=lambda self: self._compute_selection())
    company_id = fields.Many2one('res.company', string='Company', index=True, default=lambda self: self.env.company)

    @api.constrains('company_global_leave_ids')
    def _check_exist_dates(self):
        exist_product_list = []
        for global_leaves in self:
            for line in global_leaves.company_global_leave_ids:
                if datetime.datetime.strftime(line.date_from, "%Y-%m-%d") in exist_product_list:
                    raise ValidationError(_('You can not Add Twice Same Date Public Holiday'))
                exist_product_list.append(datetime.datetime.strftime(line.date_from, "%Y-%m-%d"))

    def action_public_holiday_send(self):
        self.ensure_one()
        template = self.env.ref('company_public_holidays_kanak.email_template_company_public_holidays', False)
        compose_form = self.env.ref('mail.email_compose_message_wizard_form', False)
        employee_partner = self.env['hr.employee'].search([]).mapped('user_id').mapped('partner_id')
        ctx = dict(
            default_model='company.resource.calendar',
            default_res_id=self.id,
            default_use_template=bool(template),
            default_template_id=template and template.id or False,
            default_composition_mode='mass_mail',
            user_email=self.env.user.email,
            default_partner_ids=[(6, 0, employee_partner.ids)]
        )
        return {
            'name': _('Compose Email'),
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'mail.compose.message',
            'views': [(compose_form.id, 'form')],
            'view_id': compose_form.id,
            'target': 'new',
            'context': ctx
        }

    def action_holiday_update_calendar(self):
        public_holiday = []
        Calendar = self.env['calendar.event']
        for comp_global_leave in self.company_global_leave_ids:
            public_holiday.append({
                'name': "Holiday" + "/" + comp_global_leave.name,
                'start': comp_global_leave.date_from,
                'stop': comp_global_leave.date_to,
                'categ_ids': [(6, 0, [self.env.ref('company_public_holidays_kanak.categ_meet6').id])]

            })
        for holiday in public_holiday:
            existing_calender = Calendar.search([('start', '=', holiday['start'])])
            if not existing_calender:
                Calendar.create(holiday)

    def action_holiday_update_timeoff_calendar(self):
        public_holiday = []
        holiday_id = self.env['hr.leave.type'].search([], limit=1)
        employees = self.env['hr.employee'].search([])
        # leave_calendar = self.env['hr.leave']
        leave_calendar = self.env['hr.leave']
        for comp_global_leave in self.company_global_leave_ids:
            for employee in employees:
                existing_calender = leave_calendar.search([('date_from', '=', comp_global_leave.date_from),('employee_id', '=', employee.id)])
                if not existing_calender:
                    leave_calendar.with_context(
                        tracking_disable=True,
                        mail_activity_automation_skip=True,
                        leave_fast_create=True,
                        leave_skip_state_check=True,
                    ).create({
                        'name': "Holiday" + "/" + comp_global_leave.name,
                        'date_from': comp_global_leave.date_from,
                        'date_to': comp_global_leave.date_to,
                        'holiday_status_id': holiday_id.id,
                        'employee_id': employee.id,
                        'state': 'validate'
                    })

        self.action_holiday_update_calendar()


class CompanyResourceCalendarLeaves(models.Model):
    _name = 'company.resource.calendar.leaves'
    _description = 'Company Resouce Calendar Leaves'

    name = fields.Char('Reason', required=True)
    company_calendar_id = fields.Many2one('company.resource.calendar', 'Working Hours')
    date_from = fields.Datetime('Start Date', required=True)
    date_to = fields.Datetime('End Date', required=True)
    company_id = fields.Many2one('res.company', string='Company', index=True, default=lambda self: self.env.company)

    @api.model
    def create(self, values):
        res = super(CompanyResourceCalendarLeaves, self).create(values)
        resource_calendar = self.env['resource.calendar'].search([])
        for comp_global_leave in res:
            res_cal_leaves_vals = {
                'name': comp_global_leave.name,
                'date_from': comp_global_leave.date_from,
                'date_to': comp_global_leave.date_to,
                'company_res_calendar_leaves_id': comp_global_leave.id
            }
            for calendar in resource_calendar:
                calendar.global_leave_ids = [(0, 0, res_cal_leaves_vals)]
        return res

    def write(self, values):
        resource_calendar = self.env['resource.calendar.leaves'].search(
            [('company_res_calendar_leaves_id', '=', self.id)])
        resource_calendar.write(values)
        res = super(CompanyResourceCalendarLeaves, self).write(values)
        return res

    def unlink(self):
        resource_calendar = self.env['resource.calendar.leaves'].search(
            [('company_res_calendar_leaves_id', '=', self.id)])
        resource_calendar.unlink()
        res = super(CompanyResourceCalendarLeaves, self).unlink()
        return res


class ResourceCalendarLeaves(models.Model):
    _inherit = "resource.calendar.leaves"

    company_res_calendar_leaves_id = fields.Many2one('company.resource.calendar.leaves',
                                                     string='Company Resouce Calendar')


class MailComposer(models.TransientModel):
    _inherit = 'mail.compose.message'

    employee_ids = fields.Many2many(
        'hr.employee', 'mail_compose_message_hr_employee_rel', 'wizard_id', 'employee_id', 'Employee')
