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

""" Sahana Eden Vulnerability Model

    @copyright: 2012 (c) Sahana Software Foundation
    @license: MIT

    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use,
    copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following
    conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    OTHER DEALINGS IN THE SOFTWARE.
"""

__all__ = ["S3VulnerabilityModel",
           ]

from gluon import *
from gluon.storage import Storage

from ..s3 import *

# =============================================================================
class S3VulnerabilityModel(S3Model):
    """
        Vulnerability Management
    """

    names = ["vulnerability_indicator",
             "vulnerability_aggregated_indicator",
             "vulnerability_data",
             "vulnerability_resilience_id",
             "vulnerability_ids",
             "vulnerability_resilience",
             ]

    resilience_pid = None # id of the resilience indicator
    indicator_pids = None # List of ids used to calculate the resilence indicator

    def model(self):

        T = current.T
        db = current.db

        configure = self.configure
        crud_strings = current.response.s3.crud_strings
        define_table = self.define_table
        super_link = self.super_link

        # ---------------------------------------------------------------------
        # Vulnerability Indicator
        #
        tablename = "vulnerability_indicator"
        table = define_table(tablename,
                             super_link("parameter_id", "stats_parameter"),
                             Field("posn", "integer"),
                             Field("name",
                                   label = T("Name")),
                             s3_comments("description",
                                         label = T("Description")),
                             *s3_meta_fields()
                             )

        # CRUD Strings
        ADD_VULNERABILITY = T("Add Vulnerability Indicator")
        crud_strings[tablename] = Storage(
            title_create = ADD_VULNERABILITY,
            title_display = T("Vulnerability Indicator Details"),
            title_list = T("Vulnerability Indicators"),
            title_update = T("Edit Vulnerability Indicator"),
            title_search = T("Search Vulnerability Indicators"),
            title_upload = T("Import Vulnerability Indicator"),
            subtitle_create = T("Add New Vulnerability Indicator"),
            label_list_button = T("List Vulnerability Indicators"),
            label_create_button = ADD_VULNERABILITY,
            msg_record_created = T("Vulnerability Indicator added"),
            msg_record_modified = T("Vulnerability Indicator updated"),
            msg_record_deleted = T("Vulnerability Indicator deleted"),
            msg_list_empty = T("No vulnerability indicators currently defined"))

        configure(tablename,
                  super_entity = "stats_parameter",
                  deduplicate = self.vulnerability_indicator_duplicate,
                  )

        # ---------------------------------------------------------------------
        # Vulnerability Aggregated Indicator
        #
        tablename = "vulnerability_aggregated_indicator"
        table = define_table(tablename,
                             super_link("parameter_id", "stats_parameter"),
                             Field("name",
                                   label = T("Name")),
                             s3_comments("description",
                                         label = T("Description")),
                             *s3_meta_fields()
                             )

        # CRUD Strings
        ADD_VULNERABILITY = T("Add Vulnerability Aggregated Indicator")
        crud_strings[tablename] = Storage(
            title_create = ADD_VULNERABILITY,
            title_display = T("Vulnerability Aggregated Indicator Details"),
            title_list = T("Vulnerability Aggregated Indicators"),
            title_update = T("Edit Vulnerability Aggregated Indicator"),
            title_search = T("Search Vulnerability Aggregated Indicators"),
            title_upload = T("Import Vulnerability Aggregated Indicator"),
            subtitle_create = T("Add New Vulnerability Aggregated Indicator"),
            label_list_button = T("List Vulnerability Aggregated Indicators"),
            label_create_button = ADD_VULNERABILITY,
            msg_record_created = T("Vulnerability Aggregated Indicator added"),
            msg_record_modified = T("Vulnerability Aggregated Indicator updated"),
            msg_record_deleted = T("Vulnerability Aggregated Indicator deleted"),
            msg_list_empty = T("No vulnerability aggregated indicators currently defined"))

        configure(tablename,
                  super_entity = "stats_parameter",
                  deduplicate = self.vulnerability_indicator_duplicate,
                  )

        # ---------------------------------------------------------------------
        # Vulnerability Data
        #
        tablename = "vulnerability_data"
        table = define_table(tablename,
                             super_link("data_id", "stats_data"),
                             self.stats_param_id(
                                label = T("Indicator"),
                                requires = IS_ONE_OF(db, "stats_parameter.parameter_id",
                                                     self.stats_parameter_represent,
                                                     filterby="instance_type",
                                                     filter_opts=["vulnerability_indicator"],
                                                     orderby="stats_parameter.name",
                                                     sort=True),
                                required = True
                                ),
                             self.gis_location_id(
                                widget = S3LocationAutocompleteWidget(),
                                requires = IS_LOCATION(),
                                required = True,
                             ),
                             Field("value", "double",
                                   label = T("Value"),
                                   required = True),
                             s3_date(required = True),
                             # Unused but needed for the stats_data SE
                             Field("date_end", "date",
                                   readable=False,
                                   writable=False
                                   ),
                             self.stats_group_id(),
                             *s3_meta_fields()
                             )
        # CRUD Strings
        ADD_DATA = T("Add Vulnerability Data")
        crud_strings[tablename] = Storage(
            title_create = ADD_DATA,
            title_display = T("Vulnerability Data Details"),
            title_list = T("Vulnerability Data"),
            title_update = T("Edit Vulnerability Data"),
            title_search = T("Search Vulnerability Data"),
            title_upload = T("Import Vulnerability Data"),
            subtitle_create = T("Add New Vulnerability Data"),
            label_list_button = T("List Vulnerability Data"),
            label_create_button = ADD_DATA,
            msg_record_created = T("Vulnerability Data added"),
            msg_record_modified = T("Vulnerability Data updated"),
            msg_record_deleted = T("Vulnerability Data deleted"),
            msg_list_empty = T("No vulnerability data currently defined"))

        configure(tablename,
                  super_entity = "stats_data",
                  deduplicate = self.vulnerability_data_duplicate,
                  requires_approval=True,
                  )

        # ---------------------------------------------------------------------
        # Pass model-global names to response.s3
        #
        return Storage(
                vulnerability_resilience_id = self.vulnerability_resilience_id,
                vulnerability_ids = self.vulnerability_ids,
                vulnerability_resilience = self.vulnerability_resilience,
            )

    # -------------------------------------------------------------------------
    def defaults(self):
        """ Safe defaults if the module is disabled """

        return Storage(
                vulnerability_resilience_id = lambda i: [],
                vulnerability_ids = lambda i: None,
            )

    # -------------------------------------------------------------------------
    @staticmethod
    def vulnerability_resilience_id():
        """
            Return the parameter_id of the resilience indicator
        """

        if S3VulnerabilityModel.resilience_pid is None:
            # Get the parameter_id of the aggregated_indicator
            table = current.s3db.vulnerability_aggregated_indicator
            query = (table.uuid == "Resilience") & \
                    (table.deleted == False)
            row = current.db(query).select(table.parameter_id,
                                           limitby=(0, 1)).first()
            try:
                S3VulnerabilityModel.resilience_pid = row.parameter_id
            except:
                # DB not initialised
                pass

        return S3VulnerabilityModel.resilience_pid

    # -------------------------------------------------------------------------
    @staticmethod
    def vulnerability_ids():
        """
            Return a list of the parameter_id's that are to be used when
            calculating the resilience indicator
        """

        if S3VulnerabilityModel.indicator_pids is None:
            table = current.s3db.vulnerability_indicator
            query = (table.deleted == False)
            rows = current.db(query).select(table.parameter_id)
            S3VulnerabilityModel.indicator_pids = [i.parameter_id for i in rows]

        return S3VulnerabilityModel.indicator_pids


    # -------------------------------------------------------------------------
    @staticmethod
    def vulnerability_resilience(loc_level,
                                 location_id,
                                 resilience_pid,
                                 indicator_pids,
                                 date_period_start,
                                 date_period_end,
                                 use_location,
                                 ):
        """
           Calculates the resilience held in the vulnerability_data table
           for a specific location and time period.

           This is run async

           Where appropriate add test cases to modules/unit_tests/eden/stats.py
        """

        db = current.db
        s3db = current.s3db
        vtable = s3db.vulnerability_data
        stable = s3db.stats_aggregate

        # Get the data from the vulnerability_data table
        query = (vtable.deleted != True) & \
                (vtable.approved_by != None) & \
                (vtable.parameter_id.belongs(indicator_pids))
        ward_count = 1
        if use_location:
            query &= (vtable.location_id == location_id)
        else:
            # Get all the child locations
            child_locations = current.gis.get_children(location_id, loc_level)
            child_ids = [row.id for row in child_locations]
            ward_count = len(child_ids)
            query &= (vtable.location_id.belongs(child_ids))

        if date_period_end is None:
            pass
        elif date_period_end == "None":
            date_period_end = None
        else:
            query &= (vtable.date <= date_period_end)
        rows = db(query).select(vtable.parameter_id,
                                vtable.location_id,
                                vtable.value,
                                vtable.date,
                                orderby=(vtable.location_id,
                                         vtable.parameter_id,
                                         ~vtable.date
                                         )
                                )

        # The query may return duplicate records for the same
        # location+parameter: use the most recent, which because
        # of the ordering will be the first
        values = []
        append = values.append
        locations = []
        new_location = locations.append
        last_record = (0, 0)
        for row in rows:
            value = row.value
            if not value:
                continue
            l = row.location_id
            key = (l, row.parameter_id)
            if last_record != key:
                last_record = key
                append(value)
                if l not in locations:
                    new_location(l)

        # Aggregate the values
        values_len = len(values)
        if not values_len:
            return

        import numpy

        values_sum = sum(values)
        values_min = min(values)
        values_max = max(values)
        values_avg = float(values_sum) / values_len
        values_med = numpy.median(values)
        values_mad = numpy.median([abs(v - values_med) for v in values])

        reported_count = len(locations)

        # Store Resilience value in the stats_aggregate table
        query = (stable.location_id == location_id) & \
                (stable.date == date_period_start) & \
                (stable.parameter_id == resilience_pid)
        record = db(query).select(stable.id,
                                  limitby=(0, 1)).first()

        if record:
            # Update
            db(query).update(date = date_period_start,
                             end_date = date_period_end,
                             reported_count = reported_count,
                             ward_count = ward_count,
                             min = values_min,
                             max = values_max,
                             mean = values_avg,
                             median = values_med,
                             mad = values_mad,
                             )
        else:
            # Insert new
            id = stable.insert(agg_type = 4, # indicator
                               parameter_id = resilience_pid,
                               location_id = location_id,
                               date = date_period_start,
                               end_date = date_period_end,
                               reported_count = reported_count,
                               ward_count = ward_count,
                               min = values_min,
                               max = values_max,
                               mean = values_avg,
                               median = values_med,
                               mad = values_mad,
                               )
        return

    # -------------------------------------------------------------------------
    @staticmethod
    def vulnerability_indicator_duplicate(item):
        """ Import item de-duplication """

        if (item.tablename == "vulnerability_indicator") or \
           (item.tablename == "vulnerability_aggregated_indicator"):
            table = item.table
            name = item.data.get("name", None)
            query = (table.name.lower() == name.lower())
            duplicate = current.db(query).select(table.id,
                                                 limitby=(0, 1)).first()
            if duplicate:
                item.id = duplicate.id
                item.method = item.METHOD.UPDATE

    # -------------------------------------------------------------------------
    @staticmethod
    def vulnerability_data_duplicate(item):
        """ Import item de-duplication """

        if item.tablename == "vulnerability_data":
            data = item.data
            param = data.get("parameter_id", None)
            location = data.get("location_id", None)
            date = data.get("date", None)
            table = item.table
            query = (table.parameter_id == param) & \
                    (table.location_id == location) & \
                    (table.date == date)
            duplicate = current.db(query).select(table.id,
                                                 limitby=(0, 1)).first()
            if duplicate:
                item.id = duplicate.id
                item.method = item.METHOD.UPDATE

# END =========================================================================
