# -*- coding: utf-8 -*-
from odoo import http
from odoo.http import request
from odoo.addons.web.controllers.home import Home

class CustomHome(Home):
    @http.route('/web/login', type='http', auth="public")
    def web_login(self, *args, **kw):
        response = super(CustomHome, self).web_login(*args, **kw)
        if request.params.get('login_success') and request.session.uid:
            # Use relative redirect to maintain HTTPS/HTTP protocol
            return request.redirect('/')
        return response

def render_dashboard(request):
    # 1. ROLE-BASED AUTO REDIRECTION (FOR STAFF)
    # Skip the dashboard/website entirely for Chefs and Waiters
    user = request.env.user.sudo()
    is_admin = user.has_group('base.group_system') or \
               user.has_group('dine360_restaurant.group_restaurant_admin')
    
    if not is_admin:
        # 1. WAITER / CASHIER -> Priority goes to POS
        if user.has_group('dine360_restaurant.group_restaurant_waiter') or \
           user.has_group('dine360_restaurant.group_restaurant_cashier'):
            return request.redirect('/web#action=point_of_sale.action_client_pos_menu')

        # 2. CHEF -> Directly to KDS
        if user.has_group('dine360_restaurant.group_restaurant_kitchen'):
            return request.redirect('/web#action=dine360_kds.action_kds_dashboard')

    # Remove sudo() to respect Odoo's standard menu group restrictions
    menus = request.env['ir.ui.menu'].search([
        ('parent_id', '=', False)
    ], order='sequence')

    # User role checks
    try:
        is_admin = request.env.user.has_group('base.group_system') or \
                   request.env.user.has_group('dine360_restaurant.group_restaurant_admin')
    except Exception:
        is_admin = request.env.user.has_group('base.group_system')

    # User requested to hide all standard apps and POS/KDS.
    # Only allow specific menus based on user request + admin tools.
    allowed_menus = ['Online Orders', 'Website', 'Table Reservations', 'Table Management', 'Uber Integration', 'Apps', 'Settings', 'Dine360 SaaS']
    
    # Hide 'Website' icon from the parent level Dine360Restaurants database
    if request.env.cr.dbname and 'Dine360Restaurants' in request.env.cr.dbname:
        if 'Website' in allowed_menus:
            allowed_menus.remove('Website')

    # Hide website/online orders if website module is not installed in current db
    if 'website' not in request.env:
        if 'Website' in allowed_menus:
            allowed_menus.remove('Website')
        if 'Online Orders' in allowed_menus:
            allowed_menus.remove('Online Orders')

    filtered_menus = []
    seen_names = set()
    for menu in menus:
        # Match strictly against allowed menus
        if menu.name not in allowed_menus and menu.name != 'Table Reservation':
            continue

        # Hide "Apps" and "Settings" for non-admins
        if menu.name in ['Apps', 'Settings'] and not is_admin:
            continue

        # De-duplicate by name
        if menu.name in seen_names:
            continue
        seen_names.add(menu.name)

        # Dynamic Icon Override (Dine360 Branding)
        icon_mapping = {
            'Apps': 'dine360_dashboard,static/src/img/icons/apps.svg',
            'Settings': 'dine360_dashboard,static/src/img/icons/settings.svg',
            'Table Reservation': 'dine360_dashboard,static/src/img/icons/table_reservation.svg',
            'Table Reservations': 'dine360_dashboard,static/src/img/icons/table_reservation.svg',
            'Uber Integration': 'dine360_dashboard,static/src/img/icons/uber_integration.svg',
            'Online Orders': 'dine360_dashboard,static/src/img/icons/website.svg',
            'Dine360 SaaS': 'dine360_dashboard,static/src/img/icons/saas.svg',
            'SaaS': 'dine360_dashboard,static/src/img/icons/saas.svg',
        }
        
        # Find the best match in the mapping
        current_name = menu.name
        for key, icon_path in icon_mapping.items():
            if key.lower() in current_name.lower():
                menu.web_icon = icon_path
                break

        filtered_menus.append(menu)

    # Low Stock Alerts (Ingredients)
    low_stock_products = []
    try:
        ProductTemplate = request.env['product.template'].sudo()
        if hasattr(ProductTemplate, 'get_low_stock_products'):
            low_stock_products = ProductTemplate.get_low_stock_products(limit=5)
    except Exception:
        low_stock_products = []

    values = {
        'menus': filtered_menus,
        'user_id': request.env.user,
        'low_stock_products': low_stock_products
    }
    if 'website' in request.env:
        values['website'] = request.env['website'].get_current_website()

    return request.render('dine360_dashboard.image_home_template', values)

class ImageHomeBase(http.Controller):
    @http.route('/', type='http', auth='user', website=True)
    def index(self, **kwargs):
        # Render the dashboard for logged in users when website module is not installed
        return render_dashboard(request)
