# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#
##############################################################################

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

class sale_order(models.Model):
    _inherit='sale.order'
    
    task_id = fields.Many2one('project.task',string='Field Services Task', \
                                copy=False)
    
    def services_task_values(self):
        if not self.company_id.project_id:
            raise ValidationError(_('Project - Field Service Task not configured properly !'))
            
        project_id = self.company_id.project_id and self.company_id.project_id.id \
         or False
        notes = "Notes:" + '<br/>'+"-----------------------"+'<br/>'+"Product: "\
        +'<br/><br/>'
        for line in self.order_line:
            notes += str(line.product_id.name )+" : "+ str(line.product_uom_qty)\
            +" qty" +'<br/>'
        vals = {'name':self.name,
                'partner_id': self.partner_id and self.partner_id.id or False,
                'planned_date_begin': self.date_order,
                'planned_date_end': self.date_order,
                'project_id':project_id,
                'description':notes,
                'user_id':False,
                'zone_id':self.partner_id.city_id and self.partner_id.city_id.zone_id and \
                        self.partner_id.city_id.zone_id.id or False,
                           
                }
        return vals
        
    def _prepare_project_task(self,task_values):
        project_task_ids = self.env['project.task'].create(task_values)
        self.task_id = project_task_ids.id
        return True
        
    def action_confirm(self):
        res =super(sale_order,self).action_confirm()
        task_values = self.services_task_values()
        self._prepare_project_task(task_values)
        return res

    def action_view_task(self):
        action = self.env.ref('industry_fsm.project_task_action_fsm').read()[0]
        task_id = self.mapped('task_id')
        if task_id:
            action['views'] = [
                (self.env.ref('industry_fsm.project_task_view_form').id, 'form')]
            action['res_id'] = task_id.id
        return action
    
    

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
