# -*- coding: utf-8 -*-
"""
    Sahana Eden Volunteers Management
    (Extends modules/eden/hrm.py)

    @copyright: 2012-15 (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__ = ("S3VolunteerModel",
           "S3VolunteerAwardModel",
           "S3VolunteerClusterModel",
           "vol_service_record",
           "vol_person_controller",
           "vol_volunteer_controller",
           )

try:
    # Python 2.7
    from collections import OrderedDict
except:
    # Python 2.6
    from gluon.contrib.simplejson.ordered_dict import OrderedDict

from gluon import *
from gluon.storage import Storage

from ..s3 import *
from s3layouts import S3AddResourceLink

# =============================================================================
class S3VolunteerModel(S3Model):

    names = ("vol_details",)

    def model(self):

        T = current.T
        UNKNOWN_OPT = current.messages.UNKNOWN_OPT

        availability_opts = {1: T("No Restrictions"),
                             2: T("Weekends only"),
                             3: T("School Holidays only"),
                             }

        # ---------------------------------------------------------------------
        # Volunteer Details
        # - extra details for volunteers
        #
        tablename = "vol_details"
        self.define_table(tablename,
                          self.hrm_human_resource_id(ondelete = "CASCADE"),
                          Field("volunteer_type",
                                readable = False,
                                writable = False,
                                ),
                          Field("active", "boolean",
                                default = False,
                                label = T("Active"),
                                represent = self.vol_active_represent,
                                ),
                          Field("availability", "integer",
                                label = T("Availability"),
                                represent = lambda opt: \
                                            availability_opts.get(opt,
                                                          UNKNOWN_OPT),
                                requires = IS_EMPTY_OR(
                                             IS_IN_SET(availability_opts)
                                           ),
                                ),
                          Field("card", "boolean",
                                default = False,
                                label = T("Card holder"),
                                represent = self.vol_active_represent,
                                # Enable in-template when-required
                                readable = False,
                                writable = False,
                                ),
                          *s3_meta_fields())

    # =========================================================================
    @staticmethod
    def vol_active_represent(opt):
        """ Represent the Active status of a Volunteer """

        if "report" in current.request.args:
            # We can't use a represent
            return opt

        # List view, so HTML represent is fine
        if opt:
            output = DIV(current.T("Yes"), _style="color:green")
        else:
            output = DIV(current.T("No"), _style="color:red")
        return output

# =============================================================================
class S3VolunteerAwardModel(S3Model):

    names = ("vol_award",
             "vol_volunteer_award",
             )

    def model(self):

        T = current.T
        db = current.db
        auth = current.auth

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

        ADMIN = current.session.s3.system_roles.ADMIN
        is_admin = auth.s3_has_role(ADMIN)

        root_org = auth.root_org()
        if is_admin:
            filter_opts = ()
        elif root_org:
            filter_opts = (root_org, None)
        else:
            filter_opts = (None,)

        # ---------------------------------------------------------------------
        # Volunteer Award
        #
        tablename = "vol_award"
        define_table(tablename,
                     Field("name",
                           label = T("Name"),
                           ),
                     # Only included in order to be able to set
                     # realm_entity to filter appropriately
                     self.org_organisation_id(default = root_org,
                                              readable = is_admin,
                                              writable = is_admin,
                                              ),
                     s3_comments(label = T("Description"),
                                 comment = None,
                                 ),
                     *s3_meta_fields())

        crud_strings[tablename] = Storage(
            label_create = T("Create Award"),
            title_display = T("Award"),
            title_list = T("Awards"),
            title_update = T("Edit Award"),
            title_upload = T("Import Awards"),
            label_list_button = T("List Awards"),
            label_delete_button = T("Delete Award"),
            msg_record_created = T("Award added"),
            msg_record_modified = T("Award updated"),
            msg_record_deleted = T("Award deleted"),
            msg_list_empty = T("No Awards found"))

        comment = S3AddResourceLink(c = "vol",
                                    f = "award",
                                    label = crud_strings[tablename].label_create,
                                    title = T("Award"),
                                    )

        represent = S3Represent(lookup=tablename)
        award_id = S3ReusableField("award_id", "reference %s" % tablename,
                                   label = T("Award"),
                                   requires = IS_EMPTY_OR(
                                                IS_ONE_OF(db,
                                                          "vol_award.id",
                                                          represent,
                                                          filterby="organisation_id",