# -*- coding: utf-8 -*-

import datetime

from dateutil import relativedelta

from openerp import api, fields, models, _
from openerp.exceptions import AccessError, ValidationError


class HelpdeskTicket(models.Model):
    _inherit = 'helpdesk.ticket'

    employee_ids = fields.Many2many('hr.employee', string='Employees')
    loan_ids = fields.One2many('hr.loan', 'ticket_id', string='Employee Loan')

    @api.multi
    def write(self, vals):
        res = super(HelpdeskTicket, self).write(vals)
        for ticket in self:
            if vals.get('stage_id') and self.env['helpdesk.stage'].browse(vals['stage_id']).is_close and ticket.employee_ids and not len(ticket.loan_ids):
                for employee in ticket.employee_ids:
                    values = {
                            'employee_id': employee.id,
                            'loan_type': ticket.company_id.helpdesk_loan_type_id.id,
                            'original': ticket.goods_replacement_amt,
                            'nilai_pinjaman': ticket.goods_replacement_amt/len(ticket.employee_ids),
                            'notes': ticket.description,
                            'tenor_angsuran': 1, 
                            'payment_method': 'other',
                            'ticket_id': ticket.id,
                        }
                    self.env['hr.loan'].create(values)

        return res

class HrLoan(models.Model):
    _inherit = 'hr.loan'

    ticket_id = fields.Many2one('helpdesk.ticket', string='Helpdesk Ticket')

class ResCompany(models.Model):
    _inherit = 'res.company'

    helpdesk_loan_type_id = fields.Many2one('hr.loan.type', string='Default Loan Type for Helpdesk')
