# -*- coding: utf-8 -*-
##############################################################################
#
#    Odoo, Open Source Management Solution
#    Copyright (C) 2016 Prime Consulting SA, Cape Verde (<http://prime.cv>).
#
##############################################################################

from odoo import fields, models, api

class backlog_create_task(models.TransientModel):
    _name = 'project.scrum.backlog.create.task'
    _description = 'Create Tasks from Product Backlogs'

    user_id = fields.Many2one('res.users', 'Assign To', help="Responsible user who can work on task")

    @api.multi
    def do_create(self):
        cr = self._cr
        ids = [self.id]
        context = self._context
        mod_obj = self.env['ir.model.data']
        task = self.env['project.task']
        backlog_id = self.env['project.scrum.product.backlog']
        document_pool = self.env['ir.attachment']
        ids_task = []

        data = self.read(ids, [], context=context)[0]
        backlogs = backlog_id.with_context(context).browse(context['active_ids'])
        result = mod_obj._get_id('project', 'view_task_search_form')
        id = mod_obj.read(result, ['res_id'])

        for backlog in backlogs:
            task_id = task.create({
                'product_backlog_id': backlog.id,
                'name': backlog.name,
                'description': backlog.description,
                'project_id': backlog.project_id.id,
                'user_id': data.get('user_id') and data['user_id'][0] or False,
                'planned_hours': backlog.expected_hours,
                'remaining_hours':backlog.expected_hours,
                'sequence':backlog.sequence,
            })
            document_ids = document_pool.search([('res_id', '=', backlog.id), ('res_model', '=', backlog_id._name)])
            for document_id in document_ids:
                document_pool.copy(document_id.id, default={'res_id':task_id.id, 'res_model':task._name})
            ids_task.append(task_id.id)
        return {
            'domain': "[('product_backlog_id','in',["+','.join(map(str, context['active_ids']))+"])]",
            'name': 'Tasks',
            'res_id': ids_task,
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'project.task',
            'view_id': False,
            'type': 'ir.actions.act_window',
            'search_view_id': id['res_id'],
        }

