# -*- 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_data",
             ]

    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("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 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)
                                ),
                             self.gis_location_id(),
                             Field("value", "double",
                                   label = T("Value")),
                             Field("date", "date",
                                   label = T("Date")),
                             self.doc_source_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,
                  onaccept = self.vulnerability_data_onaccept,
                  )

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

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

        return Storage()

    # -------------------------------------------------------------------------
    @staticmethod
    def vulnerability_data_onaccept(form):
        """
           When a vulnerability_data record is created then the resilience
           value, held in the stats_aggregate table, for the location needs
           to be recalculated

           This is done async as this can take some time
        """

        location_id = form.vars.location_id
        if location_id is None:
            return

        async = current.s3task.async
        # Calculate the resilience aggregate for the location
        async("vulnerability_update_resilience",
              args = [location_id])
        parents = current.gis.get_parents(location_id)
        for location in parents:
            # Calculate the aggregates for each parent
            async("vulnerability_update_resilience",
                  args = [location.id])

    # -------------------------------------------------------------------------
    @staticmethod
    def vulnerability_resilience(location_id):
        """
           Calculates the resilience held in the vulnerability_data table
           for a specific location.

           This is run async onaccept
        """

        db = current.db
        s3db = current.s3db
        vtable = s3db.vulnerability_data

        # Get the list of parameter_ids that are to be used
        itable = s3db.vulnerability_indicator
        query = (itable.deleted == False) & \
                (itable.name != "Resilience") # Would this not be better stored in a different table?
        indicators = db(query).select(itable.parameter_id)
        indicator_pids = [i.parameter_id for i in indicators]

        # Try and get the indicators from the stats_aggregate table
        atable = s3db.stats_aggregate
        count = atable.id.count()
        median = atable.median.sum()
        end_date = atable.date.max()
        query = (atable.location_id == location_id) & \
                (atable.parameter_id.belongs(indicator_pids))
        row = db(query).select(median,
                               count,
                               end_date,
                               limitby=(0, 1)).first()
        resilience = -1
        date = None
        if row[count] > 0:
            resilience = float(row[median]) / row[count]
            date = row[end_date]
        else:
            # Fallback: get the indicators from the data table
            end_date = vtable.date.max()
            query = (vtable.location_id == location_id) & \
                    (vtable.parameter_id.belongs(indicator_pids)) & \
                    (vtable.deleted != True)
            rows = db(query).select(vtable.value,
                                    end_date,
                                    groupby=vtable.location_id,
                                    )
            if len(rows) > 0:
                sum = 0.0
                count = 0
                for row in rows:
                    sum += row[vtable].value
                    count += 1
                resilience = sum / count
                date = row[end_date]

        # Store Resilience value in the database
        # Would this not be better stored in a different table?
        resilience_id = db(itable.name == "Resilience").select(itable.id,
                                                               limitby=(0, 1)).first().id
            
        query = (vtable.location_id == location_id) & \
                (vtable.parameter_id == resilience_id)
        record = db(query).select(vtable.id,
                                  limitby=(0, 1)).first()
        if record:
            db(query).update(value = resilience,
                             date = date,
                             )
            s3db.update_super(vtable, record)
        else:
            id = vtable.insert(parameter_id = resilience_id,
                               location_id = location_id,
                               data_id = data_id,
                               value = resilience,
                               date = date,
                               )
            s3db.update_super(vtable, dict(id=id))

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

        if item.tablename == "vulnerability_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 =========================================================================
