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


class ResUsers(models.Model):
    _inherit = 'res.users'

    mycompany_startup = fields.Boolean(
        string='Start with My Company',
        help='When enabled, Odoo opens the My Company hub instead of the default home.',
    )

    def action_set_mycompany_home(self):
        """Bind the My Company hub as this user's home action."""
        action = self.env.ref('my_company.action_my_company_hub')
        for user in self:
            user.sudo().write({'action_id': action.id, 'mycompany_startup': True})
        return True

    def action_clear_mycompany_home(self):
        """Remove My Company as the home action."""
        for user in self:
            user.sudo().write({
                'action_id': False,
                'mycompany_startup': False,
            })
        return True

    @api.model
    def open_hub_chat(self, user_id):
        """Open a 1:1 Discuss chat with the selected colleague."""
        target = self.browse(user_id)
        if not target.exists() or target.share:
            return False
        partner = target.partner_id
        channel_model = self.env['discuss.channel']
        channel_info = channel_model.channel_get(partners_to=[partner.id])
        if isinstance(channel_info, dict):
            channel_id = channel_info.get('id')
        else:
            channel_id = channel_info.id
        return {
            'type': 'ir.actions.act_window',
            'name': partner.name,
            'res_model': channel_model._name,
            'res_id': channel_id,
            'views': [[False, 'form']],
            'target': 'current',
        }
