# -*- coding: utf-8 -*-

"""
    Admin Controllers
"""

module = request.controller
resourcename = request.function

# S3 framework functions
# -----------------------------------------------------------------------------
def index():
    """ Module's Home Page """

    module_name = settings.modules[module].name_nice
    response.title = module_name
    return dict(module_name=module_name)

# =============================================================================
@auth.s3_requires_membership(1)
def setting():
    """
        Custom page to link to those Settings which can be edited through the web interface
    """

    return dict()

# =============================================================================
# AAA
# =============================================================================
@auth.s3_requires_membership(1)
def role():
    """
        Role Manager
    """

    # ACLs as component of roles
    s3db.add_components("auth_group",
                        **{auth.permission.TABLENAME: "group_id"}
                       )

    def prep(r):
        if r.representation != "html":
            return False
        handler = s3base.S3RoleManager()
        modules = settings.modules
        handler.controllers = Storage([(m, modules[m])
                                        for m in modules
                                        if modules[m].restricted])
        # Configure REST methods
        set_handler = r.set_handler
        set_handler("users", handler)
        set_handler("read", handler)
        set_handler("list", handler)
        set_handler("copy", handler)
        set_handler("create", handler)
        set_handler("update", handler)
        set_handler("delete", handler)
        return True
    s3.prep = prep

    s3.stylesheets.append( "S3/role.css" )
    output = s3_rest_controller("auth", "group")
    return output

# -----------------------------------------------------------------------------
def user():
    """ RESTful CRUD controller """

    table = auth.settings.table_user

    if s3_has_role("ADMIN"):
        # Needed as Admin has all roles
        pe_ids = None
    elif s3_has_role("ORG_ADMIN"):
        if settings.get_security_policy() < 6:
            # Filter users to just those belonging to the Org Admin's Org & Descendants
            otable = s3db.org_organisation
            pe_id = db(otable.id == auth.user.organisation_id).select(otable.pe_id,
                                                                      limitby=(0, 1),
                                                                      cache=s3db.cache,
                                                                      ).first().pe_id
            pe_ids = s3db.pr_get_descendants(pe_id, entity_types="org_organisation")
            pe_ids.append(pe_id)
            s3.filter = (otable.pe_id.belongs(pe_ids)) & \
                        (table.organisation_id == otable.id)
        else:
            # Filter users to just those belonging to the Org Admin's Realms
            pe_ids = auth.user.realms[auth.get_system_roles().ORG_ADMIN]
            if pe_ids:
                otable = s3db.org_organisation
                s3.filter = (otable.pe_id.belongs(pe_ids)) & \
                            (table.organisation_id == otable.id)
    else:
        auth.permission.fail()

    auth.configure_user_fields(pe_ids)

    s3db.add_components("auth_user",
                        auth_membership = "user_id")

    list_fields = ["first_name",
                   "last_name",
                   "email",
                   ]
    lappend = list_fields.append
    if len(settings.get_L10n_languages()) > 1:
        lappend("language")
    if auth.s3_has_role("ADMIN"):
        if settings.get_auth_admin_sees_organisation():
            lappend("organisation_id")
    elif settings.get_auth_registration_requests_organisation():
        lappend("organisation_id")
    if settings.get_auth_registration_requests_organisation_group():
        lappend("org_group_id")
    if settings.get_auth_registration_requests_site():
        lappend("site_id")
    link_user_to = settings.get_auth_registration_link_user_to()
    if link_user_to and len(link_user_to) > 1 and settings.get_auth_show_link():
        lappend("link_user_to")
    lappend((T("Registration"), "created_on"))
    table.created_on.represent = s3base.S3DateTime.date_represent
    lappend((T("Roles"), "membership.group_id"))

    s3db.configure("auth_user",
                   create_next = URL(c="admin", f="user", args=["[id]", "roles"]),
                   create_onaccept = lambda form: auth.s3_approve_user(form.vars),
                   list_fields = list_fields,
                   main = "first_name",
                   #update_onaccept = lambda form: auth.s3_link_user(form.vars),
                   )

    def disable_user(r, **args):
        if not r.id:
            session.error = T("Can only disable 1 record at a time!")
            redirect(URL(args=[]))

        if r.id == session.auth.user.id: # we're trying to disable ourself
            session.error = T("Cannot disable your own account!")
            redirect(URL(args=[]))

        db(table.id == r.id).update(registration_key = "disabled")
        session.confirmation = T("User Account has been Disabled")
        redirect(URL(args=[]))

    def approve_user(r, **args):
        if not r.id:
            session.error = T("Can only approve 1 record at a time!")
            redirect(URL(args=[]))

        user = db(table.id == r.id).select(limitby=(0, 1)).first()
        auth.s3_approve_user(user)

        session.confirmation = T("User Account has been Approved")
        redirect(URL(args=[r.id, "roles"]))

    def link_user(r, **args):
        if not r.id:
            session.error = T("Can only update 1 record at a time!")
            redirect(URL(args=[]))

        user = db(table.id == r.id).select(limitby=(0, 1)).first()
        auth.s3_link_user(user)

        session.confirmation = T("User has been (re)linked to Person and Human Resource record")
        redirect(URL(args=[]))

    # Custom Methods
    set_method = s3db.set_method
    set_method("auth", "user", method="roles",
               action=s3base.S3RoleManager())

    set_method("auth", "user", method="disable",
               action=disable_user)

    set_method("auth", "user", method="approve",
               action=approve_user)

    set_method("auth", "user", method="link",
               action=link_user)

    # CRUD Strings
    ADD_USER = T("Create User")
    s3.crud_strings["auth_user"] = Storage(
        label_create = ADD_USER,
        title_display = T("User Details"),
        title_list = T("Users"),
        title_update = T("Edit User"),
        title_upload = T("Import Users"),
        label_list_button = T("List Users"),
        label_delete_button = T("Delete User"),
        msg_record_created = T("User added"),
        msg_record_modified = T("User updated"),
        msg_record_deleted = T("User deleted"),
        msg_list_empty = T("No Users currently registered"))

    def rheader(r):
        if r.representation != "html":
            return None

        rheader = DIV()

        if r.record:
            id = r.id
            registration_key = r.record.registration_key
            if not registration_key:
                btn = A(T("Disable"),
                        _class = "action-btn",
                        _title = "Disable User",
                        _href = URL(args=[id, "disable"])
                        )
                rheader.append(btn)
                if settings.get_auth_show_link():
                    btn = A(T("Link"),
                            _class = "action-btn",
                            _title = "Link (or refresh link) between User, Person & HR Record",
                            _href = URL(args=[id, "link"])
                            )
                    rheader.append(btn)
            #elif registration_key == "pending":
            #    btn = A(T("Approve"),
            #            _class = "action-btn",
            #            _title = "Approve User",
            #            _href = URL(args=[id, "approve"])
            #            )
            #    rheader.append(btn)
            else:
                # Verify & Approve
                btn = A(T("Approve"),
                        _class = "action-btn",
                        _title = "Approve User",
                        _href = URL(args=[id, "approve"])
                        )
                rheader.append(btn)

            tabs = [(T("User Details"), None),
                    (T("Roles"), "roles")
                    ]
            rheader_tabs = s3_rheader_tabs(r, tabs)
            rheader.append(rheader_tabs)
        return rheader

    # Pre-processor
    def prep(r):
        if r.interactive: