# -*- coding: utf8 -*-
'''
**********************************************
*      P R O T O C O L - C L A S S
**********************************************
$RCSfile: biocase_response.py,v $
$Revision: 1307 $
$Author: j.holetschek $
$Date: 2013-07-11 14:26:20 +0200 (Do, 11. Jul 2013) $
'''

from datetime import datetime, timedelta, date
#import xml.etree.ElementTree as ET
from biocase.tools.xmlutils import element, subelement, addOptionalAttributes
from biocase.wrapper.protocol.base_response import ResponseBaseClass
from biocase.archive.general import inventory_by_dataset, ROWTYPE_DWCA

import biocase.configuration
cfg = biocase.configuration.Cfg()

import logging
log = logging.getLogger("pywrapper.protocol.inventory")


# ------------------------------------------------------------------------------------
class ResponseClass(ResponseBaseClass):
    __protocolURL__ = 'http://www.bgbm.org/biodivinf/schema/dsi_1_0.xsd'
    __protocolNS__ = 'http://www.biocase.org/schemas/dsi/1.0'

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    def __init__(self, dsaObj, diagnosticsHandler):
        ResponseBaseClass.__init__(self, dsaObj, diagnosticsHandler)
        # root element
        ns = self.__class__.__protocolNS__
        xsi = 'http://www.w3.org/2001/XMLSchema-instance'
        self.doc = element(ns, "inventory")
        addOptionalAttributes(self.doc, xsi, schemaLocation=ns + ' ' + self.__class__.__protocolURL__)
        #comment = ET.Comment("IMPORTANT NOTE: The ABCD2.06 and HISPID5 archives produced by this version of the BioCASe Provider Software are NOT dataset-aware yet. Each XML archive listed in this inventory stores all records published by the data source.")
        #self.doc[0:0] = [comment]

        # Construct inventory
        self.status = subelement(self.doc, ns, "status", "Failed")
        subelement(self.doc, ns, "created", datetime.now().isoformat())
        subelement(self.doc, ns, "service_url", self.dsaObj.getBioCASeAccessPoint())
        self.datasets = subelement(self.doc, ns, "datasets")

        # Diagnostics
        self._diagnostics = subelement(self.doc, ns, "diagnostics")

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    def setOKStatus(self):
        self.status.text = "OK"

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    def postprocessMessage(self, requestObj, dbmodVersion):
        ns = self.__class__.__protocolNS__
        if len(self.diagnosticsHandler.diagnostics) > 0:
            for d in self.diagnosticsHandler.diagnostics:
                # This check is done to skip info/debug messages that have been inserted before the DSA's debug level was loaded from config file
                if not (d.severity == 'DEBUG' and self.getPsfObj().getLogLevel() > 10) and not (d.severity == 'INFO' and self.getPsfObj().getLogLevel() > 20):
                    try:
                        subelement(self._diagnostics, ns, "diagnostic", content=d.msg.decode(self.psfObj.encoding, 'replace'), severity=d.severity, code=d.code)
                    except:
                        subelement(self._diagnostics, ns, "diagnostic", content=d.msg, severity=d.severity, code=d.code)

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    def setInventoryContent(self, datasetList):
        ns = self.__class__.__protocolNS__
        expiration_period = timedelta(self.getPsfObj().archive_expiration)

        # Check datasetList
        if datasetList == [] or datasetList == [None]:
            log.info("No datasets published by this data source.")
            self.setOKStatus()
        else:
            log.info("Listing archives for datasets %s." % (str(datasetList)))
            try:
                # Get archive list and loop through dataset list
                i = inventory_by_dataset(self.dsaObj.name)
                for datasetTitle in datasetList:
                    ds = subelement(self.datasets, ns, "dataset")
                    subelement(ds, ns, "title", datasetTitle)
                    subelement(ds, ns, "id", datasetTitle)
                    archives = subelement(ds, ns, "archives")
                    if i.has_key(datasetTitle):
                        for _schema, NS, _fname, url, rcount, filesize, mod in i[datasetTitle]:
                            if self.getPsfObj().archive_expiration:
                                exp = (mod + expiration_period).isoformat()
                            else:
                                exp = None
                            if NS is None:
                                subelement(archives, ns, "archive", url, modified=mod.isoformat(), expires=exp, rcount=rcount, filesize=filesize, rowType=ROWTYPE_DWCA)
                            else:
                                subelement(archives, ns, "archive", url, modified=mod.isoformat(), expires=exp, rcount=rcount, filesize=filesize, namespace=NS)
                # Last, set status
                self.setOKStatus()

            except Exception, err:
                log.error(err)
