# -*- coding: utf8 -*-
"""Z39.50 module for Flask-Z3950."""

from PyZ3950 import zoom
from .dataset import Dataset

__author__ = 'Alexander Mendes'
__license__ = 'BSD License'
__version__ = '0.0.1'


class Z3950Manager(object):
    """Z39.50 manager class to configure and handle Z39.50 databases.

    Args:
        app: The Flask application.

    Attributes:
        databases (dict): All configured Z3950 databases.
    """

    def __init__(self, app=None):
        self.app = app
        if app:
            self.init_app(app)


    def init_app(self, app):
        """Configure the extension.

        Args:
            app: The Flask application.
        """
        db_config = app.config.get('Z3950_DATABASES', {})

        self.databases = {}
        for name, config in db_config.items():
            db = Z3950Database(**config)
            self.databases[name] = db


class Z3950Database(object):
    """Z39.50 database class to query a Z39.50 database.

    Args:
        db: The name of the database.
        host: The host.
        port: The port.
        user (Optional): The username (the default is None).
        password (Optional): The password (the default is None).
        syntax (Optional): Prefered record syntax, supported values are USMARC,
            SUTRS, XML, GRS-1, EXPLAIN, and OPAC (the default is USMARC).
        elem_set_name (Optional): Element set name, usually B for brief or F
            for full (the default is F).

    Attributes:
        db: The name of the database.
        host: The host.
        port: The port.
        user: The username.
        password: The password.
        syntax: The prefered record syntax.
        elem_set_name: The element set name.
    """

    def __init__(self, db, host, port, user=None, password=None,
                 syntax='USMARC', elem_set_name='F'):
        self.db = db
        self.host = host
        self.port = int(port)
        self.user = user
        self.password = password
        self.syntax = syntax
        self.elem_set_name = elem_set_name


    def _connect(self):
        """Return a connection to the configured database.

        Returns:
            A connection.
        """
        conn = zoom.Connection(self.host, self.port, user=self.user,
                               password=self.password)
        conn.databaseName = self.db
        conn.preferredRecordSyntax = self.syntax
        conn.elementSetName = self.elem_set_name

        return conn


    def search(self, query, position=1, size=10, syntax='CCL'):
        """Return the results of a database query.

        Args:
            query: The database query.
            position (Optional): The position of the first record (the default
                is 1).
            size (Optional): The maximum number of records to return (the
                default is 10).
            syntax (Optional): The syntax of the query, either CCL, S-CCL, CQL,
                S-CQL, PQF, C2, ZSQL or CQL-TREE (the default is CCL).

        Returns:
            A Dataset object containing the raw data for each record.
        """
        conn = self._connect()
        try:
            q = zoom.Query(syntax, query)
        except (zoom.QuerySyntaxError) as e:
            raise zoom.QuerySyntaxError("The query could not be parsed.")

        s = int(position)
        e = s + int(size)
        rs = conn.search(q)[s:e]

        return Dataset([r.data for r in rs])

@@ -113,91 +113,8 @@
 et%0A%0A
-__author__ = 'Alexander Mendes'%0A__license__ = 'BSD License'%0A__version__ = '0.0.1'%0A%0A
 %0Acla

Remove duplicate metadata