# -*- coding: utf-8 -*-
from odoo import api, fields, models, _
from odoo.exceptions import UserError


class JbCreateTicketWizard(models.TransientModel):
    _name = 'jb.create.ticket.wizard'
    _description = 'Create Ticket Wizard'

    project_id = fields.Many2one(
        comodel_name='project.project',
        string='Project',
        required=True,
        help='Project in which to create the ticket task.',
    )
    ticket_name = fields.Char(
        string='Ticket Name',
        required=True,
        help='Name for the parent ticket task.',
    )
    task_ids = fields.Many2many(
        comodel_name='project.task',
        relation='jb_create_ticket_wizard_task_rel',
        column1='wizard_id',
        column2='task_id',
        string='Source Tasks',
        domain="[('project_id', '=', project_id)]",
        help='Tasks whose timesheet lines will be attached as subtasks on the ticket.',
    )
    planned_hours = fields.Float(
        string='Planned Hours',
        default=0.0,
        help='Planned hours for the parent ticket task.',
    )

    # ------------------------------------------------------------------
    # Onchange
    # ------------------------------------------------------------------

    @api.onchange('project_id')
    def _onchange_project_id(self):
        """Clear task selection when project changes."""
        self.task_ids = [(5, 0, 0)]

    # ------------------------------------------------------------------
    # Actions
    # ------------------------------------------------------------------

    def action_create_ticket(self):
        """Create a parent ticket task with subtasks for each selected task."""
        self.ensure_one()
        if not self.task_ids:
            raise UserError(_('Please select at least one source task.'))

        Task = self.env['project.task']

        # Create the parent ticket task
        ticket_task = Task.create({
            'name': self.ticket_name,
            'project_id': self.project_id.id,
            'is_ticket': True,
            'ticket_project_id': self.project_id.id,
            'planned_hours': self.planned_hours,
        })

        # Create subtasks, one per source task
        for task in self.task_ids:
            subtask_vals = {
                'name': task.name,
                'project_id': self.project_id.id,
                'parent_id': ticket_task.id,
                'ticket_project_id': self.project_id.id,
                'planned_hours': task.planned_hours,
                'user_ids': task.user_ids.ids,
            }
            Task.create(subtask_vals)

        return {
            'type': 'ir.actions.act_window',
            'name': _('Ticket Task'),
            'res_model': 'project.task',
            'view_mode': 'form',
            'res_id': ticket_task.id,
            'target': 'current',
        }
