# -*- coding: utf-8 -*-
# =================================================================
#
# Authors: Tom Kralidis <tomkralidis@gmail.com>
#
# Copyright (c) 2015 Tom Kralidis
#
# 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.
#
# =================================================================

import logging
from pycsw.core import util
from pycsw.core.etree import etree


LOGGER = logging.getLogger(__name__)

class OAIPMH(object):
    """OAI-PMH wrapper class"""
    def __init__(self, context, config):
        LOGGER.debug('Initializing OAI-PMH constants')
        self.oaipmh_version = '2.0'

        self.namespaces = {
            'oai': 'http://www.openarchives.org/OAI/2.0/',
            'oai_dc': 'http://www.openarchives.org/OAI/2.0/oai_dc/',
            'xsi': 'http://www.w3.org/2001/XMLSchema-instance'
        }
        self.request_model = {
            'Identify': [],
            'ListSets': ['resumptiontoken'],
            'ListMetadataFormats': ['identifier'],
            'GetRecord': ['identifier', 'metadataprefix'],
            'ListRecords': ['from', 'until', 'set', 'resumptiontoken', 'metadataprefix'],
            'ListIdentifiers': ['from', 'until', 'set', 'resumptiontoken', 'metadataprefix'],
        }
        self.metadata_formats = {
            'iso19139': {
                'namespace': 'http://www.isotc211.org/2005/gmd',
                'schema': 'http://www.isotc211.org/2005/gmd/gmd.xsd',
                'identifier': './/gmd:fileIdentifier/gco:CharacterString',
                'dateStamp': './/gmd:dateStamp/gco:DateTime|.//gmd:dateStamp/gco:Date',
                'setSpec': './/gmd:hierarchyLevel/gmd:MD_ScopeCode'
            },
            'csw-record': {
                'namespace': 'http://www.opengis.net/cat/csw/2.0.2',
                'schema': 'http://schemas.opengis.net/csw/2.0.2/record.xsd',
                'identifier': './/dc:identifier',
                'dateStamp': './/dct:modified',
                'setSpec': './/dc:type'
            },
            'fgdc-std': {
                'namespace': 'http://www.opengis.net/cat/csw/csdgm',
                'schema': 'http://www.fgdc.gov/metadata/fgdc-std-001-1998.xsd',
                'identifier': './/idinfo/datasetid',
                'dateStamp': './/metainfo/metd',
                'setSpec': './/dataset'
            },
            'oai_dc': {
                'namespace': '%soai_dc/' % self.namespaces['oai'],
                'schema': 'http://www.openarchives.org/OAI/2.0/oai_dc.xsd',
                'identifier': './/dc:identifier',
                'dateStamp': './/dct:modified',
                'setSpec': './/dc:type'
            },
            'dif': {
                'namespace': 'http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/',
                'schema': 'http://gcmd.gsfc.nasa.gov/Aboutus/xml/dif/dif.xsd',
                'identifier': './/dif:Entry_ID',
                'dateStamp': './/dif:Last_DIF_Revision_Date',
                'setSpec': '//dataset'
            },
            'gm03': {
                'namespace': 'http://www.interlis.ch/INTERLIS2.3',
                'schema': 'http://www.geocat.ch/internet/geocat/en/home/documentation/gm03.parsys.50316.downloadList.86742.DownloadFile.tmp/gm0321.zip',
                'identifier': './/gm03:DATASECTION//gm03:fileIdentifer',
                'dateStamp': './/gm03:DATASECTION//gm03:dateStamp',
                'setSpec': './/dataset'
            }
        }
        self.metadata_sets = {
            'datasets': ('Datasets', 'dataset'),
            'interactiveResources': ('Interactive Resources', 'service')
        }
        self.error_codes = {
            'badArgument': 'InvalidParameterValue',
            'badVerb': 'OperationNotSupported',
            'idDoesNotExist': None,
            'noRecordsMatch': None,
        }

        self.context = context
        self.context.namespaces.update(self.namespaces)
        self.context.namespaces.update({'gco': 'http://www.isotc211.org/2005/gco'})
        self.config = config

    def request(self, kvp):
        """process OAI-PMH request"""
        kvpout = {'service': 'CSW', 'version
': '2.0.2', 'mode': 'oaipmh'}
        LOGGER.debug('Incomin
g kvp: %s', kvp)
        if 'verb' in kvp:
            if 'metadataprefix' in kvp:
                self.metadata_prefix = kvp['metadataprefix']
                try:
                    kvpout['outputschema'] = self._get_metadata_prefix(kvp['metadataprefix'])
                except KeyError:
                    kvpout['outputschema'] = kvp['metadataprefix']
            else:
                self.metadata_prefix = 'csw-record'
            LOGGER.debug('metadataPrefix: %s', self.metadata_prefix)
            if kvp['verb'] in ['ListRecords', 'ListIdentifiers', 'GetRecord']:
                kvpout['request'] = 'GetRecords'
                kvpout['resulttype'] = 'results'
                kvpout['typenames'] = 'csw:Record'
                kvpout['elementsetname'] = 'full'
            if kvp['verb'] in ['Identify', 'ListMetadataFormats', 'ListSets']:
                kvpout['request'] = 'GetCapabilities'
            elif kvp['verb'] == 'GetRecord':
                kvpout['request'] = 'GetRecordById'
                if 'identifier' in kvp:
                    kvpout['id'] = kvp['identifier']
                if ('outputschema' in kvpout and
                    kvp['metadataprefix'] == 'oai_dc'):  # just use default DC
                    del kvpout['outputschema']
            elif kvp['verb'] in ['ListRecords', 'ListIdentifiers']:
                if 'resumptiontoken' in kvp:
                    kvpout['startposition'] = kvp['resumptiontoken']
                if ('outputschema' in kvpout and
                   kvp['verb'] == 'ListIdentifiers'):  # simple output only
                    pass #del kvpout['outputschema']
                if ('outputschema' in kvpout and
                    kvp['metadataprefix'] in ['dc', 'oai_dc']):  # just use default DC
                    del kvpout['outputschema']


                start = end = None
                LOGGER.debug('Scanning temporal parameters')
                if 'from' in kvp:
                    start = 'dc:date >= %s' % kvp['from']
                if 'until' in kvp:
                    end = 'dc:date <= %s' % kvp['until']
                if any([start is not None, end is not None]):
                    if all([start is not None, end is not None]):
                        time_query = '%s and %s' % (start, end)
                    elif end is None:
                        time_query = start
                    elif start is None:
                        time_query = end
                    kvpout['constraintlanguage'] = 'CQL_TEXT'
                    kvpout['constraint'] = time_query
        LOGGER.debug('Resulting parameters: %s', kvpout)
        return kvpout

    def response(self, response, kvp, repository, server_url):
        """process OAI-PMH request"""

        mode = kvp.pop('mode', None)
        if 'config' in kvp:
            config_val = kvp.pop('config')
        url = '%smode=oaipmh' % util.bind_url(server_url)

        node = etree.Element(util.nspath_eval('oai:OAI-P