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

""" Organisation Registry - Controllers

    @author: Fran Boon
    @author: Michael Howden

"""

prefix = request.controller
resourcename = request.function

if prefix not in deployment_settings.modules:
    session.error = T("Module disabled!")
    redirect(URL(r=request, c="default", f="index"))

# Options Menu (available in all Functions" Views)
response.menu_options = org_menu

#==============================================================================
def index():

    """ Module's Home Page """

    module_name = deployment_settings.modules[prefix].name_nice
    response.title = module_name
    return dict(module_name=module_name)


#==============================================================================
def cluster():

    """ RESTful CRUD controller """

    tablename = "%s_%s" % (prefix, resourcename)
    table = db[tablename]

    return s3_rest_controller(prefix, resourcename)


#==============================================================================
def cluster_subsector():

    """ RESTful CRUD controller """

    tablename = "%s_%s" % (prefix, resourcename)
    table = db[tablename]

    return s3_rest_controller(prefix, resourcename)


#==============================================================================
def organisation():

    """ RESTful CRUD controller """

    rheader = lambda r: shn_org_rheader(r,
                                        tabs = [(T("Basic Details"), None),
                                                (T("Staff"), "staff"),
                                                (T("Offices"), "office"),                                                
                                                (T("Warehouses"), "store"),
                                                (T("Assessments"), "assess"),
                                                (T("Projects"), "project"),
                                                (T("Activities"), "activity"),
                                                #(T("Tasks"), "task"),
                                                #(T("Donors"), "organisation"),
                                                #(T("Sites"), "site"),  # Ticket 195
                                               ])

    output = s3_rest_controller(prefix, resourcename, rheader=rheader)
    return output

#==============================================================================
def office():

    """ RESTful CRUD controller """

    tablename = "%s_%s" % (prefix, resourcename)
    table = db[tablename]

    if isinstance(request.vars.organisation_id, list):
        request.vars.organisation_id = request.vars.organisation_id[0]

    # Pre-processor
    def prep(r):
        
        if r.representation == "popup":
            organisation = request.vars.organisation_id or session.s3.organisation_id or ""
            if organisation:
                table.organisation_id.default = organisation
            
        # No point in downloading large dropdowns which we hide, so provide a smaller represent
        # the update forms are not ready. when they will - uncomment this and comment the next one
        #if r.method in ("create", "update"):
        if r.method == "create":
            table.organisation_id.requires = IS_NULL_OR(IS_ONE_OF_EMPTY(db, "org_organisation.id"))
            if request.vars.organisation_id and request.vars.organisation_id != "None":
                table.organisation_id.default = request.vars.organisation_id
        return True
    response.s3.prep = prep

    rheader = lambda r: shn_org_rheader(r,
                                        tabs = [(T("Basic Details"), None),
                                                (T("Contact Data"), "pe_contact"),
                                                (T("Staff"), "staff"),
                                               ])

    return s3_rest_controller(prefix, resourcename, rheader=rheader)


#==============================================================================
def staff():

    """ RESTful CRUD controller """

    tablename = "%s_%s" % (prefix, resourcename)
    table = db[tablename]

    # Pre-processor
    def prep(r):
        # No point in downloading large dropdowns which we hide, so provide a smaller represent
        # the update forms are not ready. when they will - uncomment this and comment the next one
        #if r.method in ("create", "update"):
        if r.method == "create":
            # person_id mandatory for a staff? We should allow room for vacant positions
            #table.person_id.requires = IS_ONE_OF_EMPTY(db, "pr_person.id")
            table.organisation_id.widget = S3AutocompleteWidget(request, "org", "organisation", post_process="load_offices(false);")
        return True
    response.s3.prep = prep

    return s3_rest_controller(prefix, resourcename)


#==============================================================================
def donor():

    """ RESTful CRUD controller """

    tablename = "%s_%s" % (prefix, resourcename)
    table = db[tablename]

    s3xrc.model.configure(table, listadd=False)
    output = s3_rest_controller(prefix, resourcename)

    return output


#==============================================================================
# Component Resources need these settings to be visible where they are linked from
# - so we put them outside their controller function
tablename = "%s_%s" % (prefix, "donor")
s3.crud_strings[tablename] = Storage(
    title_create = ADD_DONOR,
    title_display = T("Donor Details"),
    title_list = T("Donors Report"),
    title_update = T("Edit Donor"),
    title_search = T("Search Donors"),
    subtitle_create = T("Add New Donor"),
    subtitle_list = T("Donors"),
    label_list_button = T("List Donors"),
    label_create_button = ADD_DONOR,
    label_delete_button = T("Delete Donor"),
    msg_record_created = T("Donor added"),
    msg_record_modified = T("Donor updated"),