# -*- coding: utf8 -*-
'''
**********************************************
*       P R O T O C O L - C L A S S
*       for the Dataset Inventory
**********************************************
$RCSfile: biocase_protocol.py,v $
$Revision: 1260 $
$Author: j.holetschek $
$Date: 2013-02-07 11:38:43 +0100 (Do, 07. Feb 2013) $
'''

from biocase.wrapper.protocol.base_protocol import ProtocolBaseClass
from biocase.wrapper.protocol.BioCASe.biocase_request  import RequestClass
from biocase.wrapper.protocol.inventory.inventory_response import ResponseClass
from biocase.wrapper.errorclasses import NamespaceNotSupportedForDatasetInventory, InvalidNamespaceForDatasetInventory
from cgi import FieldStorage

import logging
log = logging.getLogger("pywrapper.protocol.inventory")

# ------------------------------------------------------------------------------------
class ProtocolClass(ProtocolBaseClass):
    NAME = "Dataset Inventory"

    # _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    def __init__(self, dsaObj, diagnosticsHandler):
        # Note: the request object will be a regular BioCASe request object, since we will need that later for the Scan request
        # Only protocol and response objects are of inventory type!
        ProtocolBaseClass.__init__(self, dsaObj, diagnosticsHandler, RequestClass=RequestClass, ResponseClass=ResponseClass)
        self.datasets = []

    # _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    def parseRequest(self, args):
        # First, try to find namespace parameter
        if type(args) == str:
            self.ns = args
        else:
            querystring = FieldStorage()
            if 'ns' in  querystring.keys():
                self.ns = querystring.getfirst('ns')
            else:
                log.info('Namespace parameter for dataset inventory not found; set to default http://www.tdwg.org/schemas/abcd/2.06')
                self.ns = 'http://www.tdwg.org/schemas/abcd/2.06'

        # Set the request as a scan on dataset title
        reqString = """<?xml version='1.0' encoding='UTF-8'?>
            <request xmlns='http://www.biocase.org/schemas/protocol/1.3'>
                <header><type>scan</type></header>
                <scan>
                    <requestFormat>%s</requestFormat>
                    <concept>/DataSets/DataSet/Metadata/Description/Representation/Title</concept>
                </scan>
            </request>""" % (self.ns)
        self.requestObj.parseRequest({'request_string': reqString})
        log.debug(self.requestObj)

    # _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    def processRequest(self):
        # First, check namespace
        if self.ns in ['http://www.tdwg.org/schemas/abcd/2.06', 'http://www.chah.org.au/schemas/hispid/5']:
            if self.ns in self.psfObj.schemas:
                log.info("Dataset Inventory for namespace %s requested. Executing Scan on Dataset Title." % (self.ns))
            else:
                raise NamespaceNotSupportedForDatasetInventory(self.ns)
        else:
            raise InvalidNamespaceForDatasetInventory(self.ns)

        # chose DBmodule, connect to DB
        from biocase.wrapper.operations import getOperationsObjectForDBMod
        operationObj = getOperationsObjectForDBMod(self.psfObj, self.responseObj)
        # Execute scan
        self.datasets = [d for d in operationObj.scan(self.requestObj) if d is not None]
        # Construct Inventory
        self.responseObj.setInventoryContent(self.datasets)
