# -*- coding: utf-8 -*-
# Copyright 2012-2017 Luc Saffre
# License: BSD (see file COPYING for details)
"""Some diagnostic utilities."""

from __future__ import unicode_literals
from builtins import str
from builtins import object
import six

# from textwrap import fill
from atelier import rstgen
from atelier.utils import unindent

from django.conf import settings
from django.utils.encoding import force_text

from lino.core.layouts import BaseLayout
from lino.core.elems import Container, Wrapper, FieldElement
from lino.modlib.users.choicelists import UserTypes
from lino.core import actors
from lino.core import actions
from lino.core.utils import get_models
from lino.core.utils import full_model_name as fmn
from lino.api import dd


class Analyzer(object):
    "The class of the :data:`lino.utils.diag.analyzer` object."
    def __init__(self):
        self._initialized = False

    def analyze(self):
        if self._initialized:
            return
        self._initialized = True
        window_actions = dict()
        self.custom_actions = []
        for a in actors.actors_list:
            for ba in a.get_actions():
                if ba.action.is_window_action():
                    wl = ba.get_window_layout() or ba.action.params_layout
                    if wl is not None:
                        if isinstance(wl, six.string_types):
                            raise Exception("20150323 : {0}".format(ba))
                            # Was used to find Exception: 20150323 :
                            # <BoundAction(checkdata.Checkers,
                            # <ShowDetail detail (u'Detail')>)>

                        if wl not in window_actions:
                            # lh = wl.get_layout_handle(ui)
                            # for e in lh.main.walk():
                            #     e.loosen_requirements(a)
                            window_actions[wl] = ba
                else:  # if ba.action.custom_handler:
                    self.custom_actions.append(ba)
        l = list(window_actions.values())

        def f(a):
            return str(a.full_name())
        self.window_actions = list(sorted(l, key=f))
        self.custom_actions = list(sorted(self.custom_actions, key=f))
    
    def show_window_fields(self):
        self.analyze()
        items = []
        for ba in analyzer.window_actions:
            items.append(
                "{0} : {1}".format(
                    ba.full_name(), layout_fields(ba)))

        return rstgen.ul(items)

    def show_window_permissions(self):