from odoo import fields, models, api
from odoo.exceptions import AccessError


class Users(models.Model):
    _inherit = "res.users"

    position = fields.Char(string='Position')
    type = fields.Selection([
        ('admin', 'Admin'),
        ('moderator', 'Moderator'),
        ('reader', 'Reader'),
    ], string='User Type', required=True, default='reader')
    
    role = fields.Selection([
        ('republic', 'Republic'),
        ('region', 'Region'),
        ('district', 'District'),
        ('mahalla', 'Mahalla'),
    ], string='Role', default='mahalla')
    
    region_id = fields.Many2one('region', string="Region")
    district_id = fields.Many2one('district', string="District")
    mahalla_id = fields.Many2one('mahalla', string="Mahalla")

    @api.onchange('type')
    def _onchange_type(self):
        if self.type == 'admin':
            self.role = False
            self.region_id = False
            self.district_id = False
            self.mahalla_id = False
        self._update_role_visibility()
    
    @api.onchange('role')
    def _onchange_role(self):
        if self.type != 'admin':
            self._update_role_visibility()
    
    def _update_role_visibility(self):
        if self.type == 'admin':
            pass
        elif self.role == 'republic':
            pass
        elif self.role == 'region':
            self.district_id = False
            self.mahalla_id = False
        elif self.role == 'district':
            self.mahalla_id = False
        elif self.role == 'mahalla':
            pass

    def action_change_password(self):
        self.ensure_one()
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'change.password.wizard',
            'view_mode': 'form',
            'view_id': self.env.ref('base.change_password_wizard_view').id,
            'target': 'new',
            'context': {'default_user_id': self.id},
        }

    def assign_group_based_on_role(self):
        self.ensure_one()

        super_admin_group = self.env.ref('mahallam.group_super_admin')
        moderator_group = self.env.ref('mahallam.group_moderator')
        reader_group = self.env.ref('mahallam.group_reader')
        republic_moderator_group = self.env.ref('mahallam.group_republic_moderator')
        republic_reader_group = self.env.ref('mahallam.group_republic_reader')
        region_moderator_group = self.env.ref('mahallam.group_region_moderator')
        region_reader_group = self.env.ref('mahallam.group_region_reader')
        district_moderator_group = self.env.ref('mahallam.group_district_moderator')
        district_reader_group = self.env.ref('mahallam.group_district_reader')
        mahalla_moderator_group = self.env.ref('mahallam.group_mahalla_moderator')
        mahalla_reader_group = self.env.ref('mahallam.group_mahalla_reader')

        self.groups_id = [(3, super_admin_group.id), (3, moderator_group.id), (3, reader_group.id),
                            (3, republic_moderator_group.id), (3, republic_reader_group.id),
                            (3, region_moderator_group.id), (3, region_reader_group.id),
                            (3, district_moderator_group.id), (3, district_reader_group.id),
                            (3, mahalla_moderator_group.id), (3, mahalla_reader_group.id)]

        if self.type == 'admin':
            self.groups_id = [(4, super_admin_group.id)]
        elif self.type == 'moderator':
            self.groups_id = [(4, moderator_group.id)]
            if self.role == 'republic':
                self.groups_id = [(4, republic_moderator_group.id)]
            elif self.role == 'region':
                self.groups_id = [(4, region_moderator_group.id)]
            elif self.role == 'district':
                self.groups_id = [(4, district_moderator_group.id)]
            elif self.role == 'mahalla':
                self.groups_id = [(4, mahalla_moderator_group.id)]
        elif self.type == 'reader':
            self.groups_id = [(4, reader_group.id)]
            if self.role == 'republic':
                self.groups_id = [(4, republic_reader_group.id)]
            elif self.role == 'region':
                self.groups_id = [(4, region_reader_group.id)]
            elif self.role == 'district':
                self.groups_id = [(4, district_reader_group.id)]
            elif self.role == 'mahalla':
                self.groups_id = [(4, mahalla_reader_group.id)]

    @api.model
    def create(self, vals):
        user = super(Users, self).create(vals)
        user.assign_group_based_on_role()
        return user

    def write(self, vals):
        res = super(Users, self).write(vals)
        if 'type' in vals or 'role' in vals:
            self.assign_group_based_on_role()
        return res<?xml version="1.0" encoding="utf-8"?>
<odoo>
    <data>
        <!-- Tree View -->
        <record id="view_user_tree_custom" model="ir.ui.view">
            <field name="name">res.users.tree</field>
            <field name="model">res.users</field>
            <field name="arch" type="xml">
                <tree string="Users" default_order="create_date desc">
                    <field name="name"/>
                    <field name="type"/>
                    <field name="role"/>
                    <field name="position"/>
                    <field name="login"/>
                    <field name="phone"/>
                </tree>
            </field>
        </record>
        <!-- Form View -->
        <record id="view_user_form_custom" model="ir.ui.view">
            <field name="name">res.users.form.custom</field>
            <field name="model">res.users</field>
            <field name="priority" eval="1"/>
            <field name="arch" type="xml">
                <form>
                    <header>
                        <button string="Set Password"
                                type="object" name="action_change_password"
                                class="btn-primary"
                                invisible="id == False"/>
                    </header>
                    <sheet>
                        <div class="oe_avatar_group">
                            <field name="image_1920" widget="image" class="oe_avatar"/>
                        </div>
                        <group>
                            <group>
                                <field name="name" required="1"/>
                                <field name="email" invisible="1"/>
                                <field name="login" required="1"/>
                                <field name="phone" placeholder="+998 xx xxx xx xx"/>
                                <field name="type" required="1"/>
                                <field name="position" invisible="type == 'admin'"/>
                                <field name="role" 
                                        invisible="type == 'admin'" 
                                        required="type != 'admin'"/>
                                
                                <field name="region_id" 
                                        invisible="type == 'admin' or role != 'region' and role != 'district' and role != 'mahalla'" 
                                        required="role in ['region', 'district', 'mahalla']"
                                        />
                                
                                <field name="district_id"
                                        invisible="type == 'admin' or role != 'district' and role != 'mahalla'" 
                                        required="role in ['district', 'mahalla']"
                                        domain="[('region_id', '=', region_id)]"/>
                                
                                <field name="mahalla_id" 
                                        invisible="type == 'admin' or role != 'mahalla'" 
                                        required="role == 'mahalla'"
                                        domain="[('district_id', '=', district_id)]"/>
                                <separator string="Access Rights" colspan="4" invisible="type == 'admin'"/>
                                <field name="groups_id" widget="many2many_checkboxes" options="{'no_create': True}">
                                    <tree editable="bottom">
                                        <field name="name"/>
                                        <field name="category_id"/>
                                    </tree>
                                </field>
                            </group>
                        </group>
                    </sheet>
                </form>
            </field>
        </record>

        <!-- Kanban View -->
        <record id="view_user_kanban_custom" model="ir.ui.view">
            <field name="name">res.users.kanban</field>
            <field name="model">res.users</field>
            <field name="arch" type="xml">
                <kanban>
                    <field name="id"/>
                    <field name="image_1920"/>
                    <field name="name"/>
                    <field name="type"/>
                    <field name="role"/>
                    <field name="position"/>
                    <templates>
                        <t t-name="kanban-box">
                            <div class="oe_kanban_global_click o_kanban_record_has_image_fill o_res_partner_kanban">
                                <div class="o_kanban_image_fill_left d-none d-md-block"
                                    t-attf-style="background-image:url(#{kanban_image('res.users', 'image_128', record.id.raw_value)})"
                                    role="img"/>
                                <div class="oe_kanban_details">
                                    <strong class="o_kanban_record_title">
                                        <field name="name"/>
                                    </strong>
                                    <div>
                                        <strong>Type: </strong><field name="type"/>
                                    </div>
                                    <div t-if="record.role.raw_value">
                                        <strong>Role: </strong><field name="role"/>
                                    </div>
                                    <div t-if="record.position.raw_value">
                                        <strong>Position: </strong><field name="position"/>
                                    </div>
                                </div>
                            </div>
                        </t>
                    </templates>
                </kanban>
            </field>
        </record>

        <!-- Actions -->
        <record id="action_user_custom" model="ir.actions.act_window">
            <field name="name">Users</field>
            <field name="res_model">res.users</field>
            <field name="view_mode">form</field>
            <field name="view_id" ref="view_user_form_custom"/>
        </record>

        <record id="action_user_list" model="ir.actions.act_window">
            <field name="name">Users</field>
            <field name="res_model">res.users</field>
            <field name="view_mode">kanban,tree</field>
            <field name="view_id" ref="view_user_tree_custom"/>
        </record>

        <!-- Menus -->
        <menuitem
            id="user_menu"
            name="User Management"
            sequence="1"/>

        <menuitem
            id="user_managers_menu"
            name="Users"
            parent="user_menu"
            action="action_user_list"
            sequence="1"/>

        <menuitem
            id="user_add_menu"
            name="Add User"
            parent="user_menu"
            action="action_user_custom"
            sequence="2"/>
    </data>
</odoo> i wanna set domain to groups id, it should show the groups that have both users, except admin user