from odoo import fields, models, api, _
from odoo.exceptions import UserError, ValidationError
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta


class ServiceRequestInherit(models.Model):
    _inherit = 'service.request'

    project_id = fields.Many2one('project.project', srting='Project')
    project_expected_delivery_date = fields.Date(string='Expected Delivery Date', related='project_id.date', )
    rent_period = fields.Integer('Rent Period')
    project_create = fields.Boolean(string='Project Create?', related='service_cat.project_create')
    project_state = fields.Selection(string='Project Status',
                                     selection=[('new', 'New'), ('open', 'Running'), ('hold', 'Hold'),
                                                ('close', 'Closed')],
                                     compute='_compute_project_state', store=True, )

    @api.depends('project_id.status')
    def _compute_project_state(self):
        for rec in self:
            rec.project_state = rec.project_id.status
            if rec.project_id.status == 'close':
                rec.state = 'send_request_to_supplier'

    def action_create_project(self):
        super(ServiceRequestInherit, self).action_create_project()
        for rec in self:
            if rec.project_create and not rec.project_id:
                project = self.env['project.project'].sudo().create(
                    {
                        'name': (
                                        _('%s') % rec.service_cat.service_name) + "/" + rec.family_id.name + "/" + rec.family_id.code,
                        'partner_id': rec.service_producer_id.id,
                        'beneficiary_id': rec.family_id.partner_id.id,
                        'category_id': rec.service_cat.category_id.id,
                        'requested_service_amount': rec.requested_service_amount,
                        'service_type': rec.service_cat.service_type,
                        'department_execute_id': rec.family_id.branch_custom_id.branch.id,
                        'project_latitude': rec.family_id.lat,
                        'project_longitude': rec.family_id.lon,
                        'street': rec.family_id.street,
                        'street2': rec.family_id.house_number,
                        'city': rec.family_id.city_id.name,
                        'state_id': rec.family_id.city_id.state_id.id,
                        'zip': rec.family_id.zip,
                        'country_id': rec.family_id.city_id.country_id.id,
                    }
                )
                rec.project_id = project
