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

"""
    Sahana Eden Vulnerability Controller
"""

module = request.controller
resourcename = request.function

if not settings.has_module(module):
    raise HTTP(404, body="Module disabled: %s" % module)

# @ToDo: deployment_setting
#countries = ["TL", "VN"]
countries = ["VN"]

# -----------------------------------------------------------------------------
def index():
    """ Module Home Page: Map """

    # This module uses it's own Theme
    settings.base.theme = "Vulnerability"

    # Additional scripts
    append = s3.scripts.append
    append("/%s/static/scripts/yepnope.1.5.4-min.js" % appname)
    if s3.debug:
        append("/%s/static/scripts/jquery.ui.selectmenu.js" % appname)
        append("/%s/static/scripts/jquery.ui.progressbar.js" % appname)
        append("/%s/static/scripts/TypeHelpers.js" % appname)
        append("/%s/static/scripts/S3/s3.vulnerability.js" % appname)
        append("/%s/static/scripts/S3/s3.dataTables.js" % appname)
        append("/%s/static/scripts/jquery.dataTables.js" % appname)
        append("/%s/static/scripts/jquery.dataTables.fnSetFilteringDelay.js" % appname)
        append("/%s/static/scripts/flot/jquery.flot.js" % appname)
        append("/%s/static/scripts/flot/jquery.flot.fillbetween.js" % appname)
        append("/%s/static/scripts/flot/jquery.flot.crosshair.js" % appname)
    else:
        append("/%s/static/scripts/S3/s3.vulnerability.min.js" % appname)
        append("/%s/static/scripts/S3/s3.dataTables.min.js" % appname)
        append("/%s/static/scripts/flot/jquery.flot.min.js" % appname)
        append("/%s/static/scripts/flot/jquery.flot.crosshair.min.js" % appname)

    js_global = []
    append = js_global.append

    # i18n
    i18n = "\n".join((
        "S3.i18n.gis_requires_login='%s'" % T("Requires Login"),
        "S3.i18n.no_matching_result='%s'" % T("No matching result"),
        "S3.i18n.no_entries_found='%s'" % T("No Entries Found"),
        "S3.i18n.loading_report_details='%s'" % T("Loading report details"),
        "S3.i18n.choose='%s'" % T("Choose"),
        "S3.i18n.population='%s'" % T("Population"),
        "S3.i18n.reported='%s'" % T("Reported"),
        "S3.i18n.country='%s'" % COUNTRY,
        "S3.i18n.country_in='%s'" % T("Country in"),
        "S3.i18n.show_more='%s'" % T("Show more"),
        "S3.i18n.show_less='%s'" % T("Show less"),
        "S3.i18n.submit_data='%s'" % T("Submit Data"),
        "S3.i18n.analysis='%s'" % T("Analysis"),
        "S3.i18n.reports='%s'" % T("Reports"),
        "S3.i18n.all_reports='%s'" % T("All reports"),
        "S3.i18n.my_reports='%s'" % T("My reports"),
        "S3.i18n.approval_request_submitted='%s'" % T("Approval request submitted"),
        "S3.i18n.thankyou_for_your_approval='%s'" % T("Thank you for your approval"),
        "S3.i18n.reject_request_submitted='%s'" % T("Reject request submitted"),
        "S3.i18n.submission_has_been_declined='%s'" % T("Thank you, the submission%(br)shas been declined") % dict(br="<br />"),
        "S3.i18n.last_data_collected_on='%s'" % T("Last Data Collected on"),
        "S3.i18n.by='%s'" % T("by"),
        "S3.i18n.in_='%s'" % T("in"),
        "S3.i18n.in_this='%s'" % T("in this"),
        "S3.i18n.of='%s'" % T("of"),
        "S3.i18n.out_of='%s'" % T("out of"),
        "S3.i18n.review='%s'" % T("Review"),
        "S3.i18n.go_to_the='%s'" % T("Go to the"),
        "S3.i18n.select_data_type='%s'" % T("Select data type"),
        "S3.i18n.about_to_submit_indicator_ratings='%s'" % T("You are about to submit indicator ratings for"),
        "S3.i18n.poor='%s'" % T("poor"),
        "S3.i18n.fair='%s'" % T("fair"),
        "S3.i18n.moderate='%s'" % T("moderate"),
        "S3.i18n.strong='%s'" % T("strong"),
        "S3.i18n.data_quality='%s'" % T("Data Quality"),
        "S3.i18n.of_total_data_reported='%s'" % T("of total data reported"),
        "S3.i18n.uploading_report_details='%s'" % T("Uploading report details"),
        "S3.i18n.upload_successful='%s'" % T("Upload successful"),
        ))
    append(i18n)

    # Get the L0 hdata & summary vdata
    hdata, vdata = l0()

    # Get the default location to open the map
    bounds = None
    root_org = auth.root_org()
    start = False
    if root_org:
        otable = s3db.org_organisation
        ttable = s3db.gis_location_tag
        gtable = s3db.gis_location
        query = (otable.id == root_org) & \
                (ttable.tag == "ISO2") & \
                (ttable.value == otable.country)
        r = db(query).select(ttable.location_id,
                             limitby=(0, 1)).first()
        if r and r.location_id in countries:
            start = True
            append('''\nstart=%s''' % r.location_id)
            # Add the child L1 summary vdata
            l1(r.location_id, vdata)
    if not start:
        append('''\nstart=""''')

    dumps = json.dumps
    script = '''
hdata=%s
vdata=%s
''' % (dumps(hdata), dumps(vdata))
    append(script)

    # Get the list of indicators
    itable = s3db.vulnerability_indicator
    query = (itable.deleted == False)
    rows = db(query).select(itable.name,
                            itable.description,
                            itable.parameter_id,
                            orderby=itable.posn)
    indicators = OrderedDict()
    count = 1
    for row in rows:
        indicators[count] = dict(i=row.parameter_id,
                                 n=row.name,
                                 d=row.description)
        count += 1

    append('''idata=%s''' % json.dumps(indicators))

    s3.js_global.append("".join(js_global))

    # Reports
    from s3.s3utils import S3DataTable
    resource = s3db.resource("stats_group")
    list_fields = ["id",
                   "date",
                   "location_id",
                   "location_id$L2",
                   "group",
                   "group_type_id",
                   "created_by",
                   "approved_by",
                   ]
    rfields = resource.resolve_selectors(list_fields)[0]
    filteredrows = resource.count()
    dt = S3DataTable(rfields, [])
    level_1_titles = [["Approval pending", T("Approval pending")],
                      ["VCA Report",T("VCA Report")],
                      ["Report",T("Report")],
                      ]
    report = dt.html(filteredrows,
                     filteredrows,
                     "report",
                     dt_pagination = "false",
                     dt_bFilter = "false",
                     dt_sDom = "t",
                     dt_group = [4, 3],
                     dt_group_totals = [level_1_titles],
                     dt_ajax_url = URL(c="vulnerability",
                                       f="report",
                                       extension="aadata",
                                       vars={"id": "report"},
                                       ),
                     dt_action_col = -1,
                     dt_group_space = "true",
                     dt_shrink_groups = "accordion",
                     dt_group_types = ["text", "none"],
                     )
    s3.report = report

    user = auth.user
    if user:
        user_name = "%s %s" % (user.first_name, user.last_name)
    else:
        user_name = ""
    today = request.utcnow.strftime("%d-%b-%y")
    response.view = "vulnerability/map.html"
    return dict(indicators=indicators,
                user_name = user_name,
                today = today,
                COUNTRY = COUNTRY.upper(),
                CHOOSE_COUNTRY = T("Choose Country"))

# -----------------------------------------------------------------------------
def init():
    """
        Create the static GeoJSONs that the app needs
    """

    gis.export_admin_areas(countries)
    return "complete"

# -----------------------------------------------------------------------------
def l0():
    """
        Return hdata (Hierarchy Labels) & summary vdata (Resilience) for all Countries
        - used only by the initial map load
    """

    gtable = s3db.gis_location
    ttable = s3db.gis_location_tag
    htable = s3db.gis_hierarchy
    query = (gtable.id == ttable.location_id) & \
            (ttable.tag == "ISO2") & \
            (ttable.value.belongs(countries)) & \
            (gtable.id == htable.location_id)
    stable = s3db.stats_aggregate
    lquery = (stable.parameter_id == s3db.vulnerability_resilience_id()) & \
             (stable.agg_type == 4) & \
             (stable.location_id == gtable.id)
    left = stable.on(lquery)
    hdata = {}
    vdata = {}

    ids = []
    append = ids.append
    rows = db(query).select(gtable.id,
                            gtable.name,
                            htable.L1,
                            htable.L2,
                            htable.L3,
                            #htable.L4,
                            stable.date,
                            stable.mean,
                            orderby=~stable.date,
                            left=left)
    for row in rows:
        id = row[gtable].id
        if id in ids:
            # We're only interested in the most recent data per location
            continue
        append(id)
        _grow = row[gtable]
        _hrow = row[htable]
        hdata[id] = dict(l1 = _hrow.L1,
                         l2 = _hrow.L2,
                         l3 = _hrow.L3,
                         #l4 = _hrow.L4,
                         )
        mean = row[stable].mean
        if mean is None:
            resilience = 0
        else:
            resilience = int(round(mean, 0))
        vdata[id] = dict(r = resilience,
                         n = _grow.name,
                         l = 0,
                         )

    return hdata, vdata

# -----------------------------------------------------------------------------
def l1(id, vdata):
    """
        Update summary vdata (Resilience) for all child L1s of the start country
        - used only by the initial map load
    """

    gtable = db.gis_location
    query = (gtable.parent == id) & \
            (gtable.level == "L1")
    atable = db.vulnerability_aggregated_indicator
    stable = db.stats_aggregate
    rquery = (atable.name == "Resilience") & \
             (stable.parameter_id == atable.parameter_id) & \
             (stable.agg_type == 4)
    rows = db(query).select(gtable.id,
                            gtable.name,
                            )
    for row in rows:
        query = rquery & (stable.location_id == row.id)
        _row = db(query).select(stable.date,
                                stable.mean,
                                orderby=~stable.date).first()
        resilience = None
        if _row and _row.mean is not None:
            resilience = int(round(_row.mean, 0))
        vdata[row.id] = dict(r = resilience,
                             n = row.name,
                             l = 1,
                             f = id,
                             )

    return

# -----------------------------------------------------------------------------
def vdata():
    """
        Return JSON of the Vulnerability data for a location
        - for display in Map Popups and the Drawer

        vdata = { id : {
                        'n' : name,
                        'l' : level,
                        'f' : parent,
                        'r' : resilience,
                        'i' : indicator data,
                        'c' : count (how many L3s reported in this region),
                        't' : count (how many L3s total in this region),
                        'q' : quality,
                        'p' : population,
                        's' : source (for population),
                        'b' : population breakdown (for L3s),
                        'd' : date last collected (for L3s),
                        'w' : collected by (for L3s),
                        }
                 }
    """

    try:
        id = request.args[0]
    except:
        raise HTTP(400)

    gtable = s3db.gis_location
    query = (gtable.id == id)
    row = db(query).select(gtable.name,
                           gtable.level,
                           gtable.parent,
                           gtable.L0,
                           gtable.L1,
                           gtable.L2,
                           #gtable.L3,
                           limitby=(0, 1)).first()
    if not row or not row.level:
        return ""
    script = ""
    data = dict(
            n = row.name,
            l = int(row.level[1]),
            f = row.parent,
            )
    vdata = {}
    ids = []
    append = ids.append
    level = row.level
    l0_name = row.L0
    l1_name = row.L1
    l2_name = row.L2