# -*- coding: utf-8 -*-
##############################################################################
#
#    Author: João Jerónimo (joao.jeronimo.pro@gmail.com)
#    Copyright (C) 2019-2022 - Licensed under the terms of GNU LGPL
#
##############################################################################

from odoo import models, fields, api, tools, SUPERUSER_ID

"""
This module contains tools for:
 * Interpreting contextual user, company, etc;
 * Interpreting contextual actions;
 * Building exit actions for button;
 * Other features alike.
"""

def context2objects(env, context, assert_model=False):
    """
    Returns caller object(s) if any.
    Can also assert being called from a specific model. In this case, when called
    from an action that was generated by any other model, the method will return
    a null record.
    """
    #breakpoint()
    caller_model = context.get('active_model')
    if assert_model and caller_model!=assert_model:
        return env[assert_model]
    elif not caller_model:
        return None
    involved_objects = env[caller_model].browse(
        context.get('active_ids', [])
        )
    return involved_objects

def default_company(self, caller_obj=None, hinting_field=None):
    """
    General method that returns a default company on record creation.
    self            The record set.
    caller_obj      Optionally, when the window was crated by an
                    action button. Use context2objects() method to get
                    the caller object easily.
    hinting_field   Optional name of a field to get the company from.
    """
    # Try to get company from caller:
    if caller_obj and 'company_id' in dir(caller_obj):
        caller_company = getattr(caller_obj, 'company_id')
        if caller_company:
            return caller_company
    # Try to get company from a field:
    if hinting_field:
        hinting_value = getattr(self, hinting_field)
        if hinting_value and 'company_id' in dir(hinting_value):
            hinting_field_company = getattr(hinting_value, 'company_id')
            if hinting_field_company:
                return hinting_field_company
    # If nothing else works, get a company from the current loggen-in user:
    return self.env.company

def gen_record_viewing_action(env, window_action_template_xid, objects_domain=False, always_tree=False):
    """
    Generates a window action that shows given record(s) to the user.
    window_action_template_xid      XID of an existing window action to use as a template.
    objects_domain                  Domain for record to show.
    """
    EnvRef = env.ref
    ret_act = EnvRef(window_action_template_xid).read()[0]
    # Getting useful information from the window action:
    model_name = ret_act['res_model']
    # Restricting domain to show:
    if objects_domain:
        ret_act['domain'] = objects_domain
        # Showing form view when a single record fits:
        if not always_tree and (env[model_name].search_count(objects_domain) == 1):
            single_record = env[model_name].search(objects_domain, limit=1)
            # Set the view as form-only by removing other view pairs (note: setting 'view_mode' field does not work):
            ret_act['views'] = [ view_pair for view_pair in ret_act['views'] if view_pair[1]=='form' ]
            ret_act['res_id'] = single_record.id
    return ret_act
    

def gen_record_viewing_action_buggy(objects, action_title, window_action_template_xid=False, always_tree=False, tree_view_xid=False, form_view_xid=False, other_views=[]):
    """
    Generates a window action that shows given record(s) to the user.
    action_title                Name for the window to show.
    objects                     Odoo recordset of record to show as tree or form view.
    window_action_template_xid  Optional XID of an existing window action to use as a template.
    tree_view_xid               Optional XID of tree view to use.
    form_view_xid               Optional XID of form view to use.
    other_views                 Optional list of pairs for additional views: (view_id, 'view_type')
    """
    EnvRef = objects.env.ref
    model_name = objects._name
    # Get the window action to use as template if requested:
    if window_action_template_xid:
        ret_act = EnvRef(window_action_template_xid).read()[0]
    else:
        ret_act = {}
    # Augment the window action with data provided as arguments:
    ret_act.update({
        'name': action_title,
        'type': 'ir.actions.act_window',
        'res_model': model_name,
        'domain': [('id', 'in', objects.ids),],
        "views": [
            (False, "tree"),
            (False, "form"),
            ],
        })
    if tree_view_xid or form_view_xid or len(other_views)>0:
        ret_act.update({
            'views': [
                *( [(EnvRef(tree_view_xid).id, 'tree')] if tree_view_xid else [] ),
                *( [(EnvRef(form_view_xid).id, 'form')] if form_view_xid else [] ),
                *other_views,
                ],
            })
    # Make the action tree or form depending on the number of records:
    if len(objects) == 1 and not always_tree:
        ret_act.update({
            'view_type': 'form',
            'view_mode': 'form',
            'res_id': objects.id,
            })
    else:
        ret_act.update({
            'view_type': 'tree',
            'view_mode': 'tree',
            })
    return ret_act
