"""
A library management tool
"""
from argparse import ArgumentParser
import json
import logging
import os
from pathlib import Path
import sqlite3

from librarylib.database import SCHEMA

LIBRARY = Path(os.path.expanduser('~/')) / '.liblib'


def initialize(topics_file, location=LIBRARY, force=False):
    """
    Create a new database.

    topics_file: The path to a json file containing lcc topics.
    location: (optional, ~/.liblib) Where to create the database.
    force: (optional, False) Overwrite existing file at location
    """
    if location.exists():
        if force:
            os.remove(location.as_posix())
        else:
            logging.error("Database already exists")
            raise ValueError(topics_file)

    cursor = sqlite3.connect(location.as_posix()).cursor()

    cursor.connection.executescript(SCHEMA)

    with topics_file.open() as fileobj:
        data = json.load(fileobj)

    for class_symbol, classification in data.items():
        cursor.execute(
            'INSERT INTO classes (symbol, description) '
            'VALUES (:symbol, :description);',
            {
                'symbol': class_symbol,
                'description': classification['description']
            }
        )

        for subclass_symbol, topics in classification['subclasses'].items():

            for topic in topics:
                topic['class_symbol'] = class_symbol
                topic['subclass_symbol'] = subclass_symbol

                cursor.execute(
                    'INSERT INTO topics (class_symbol, subclass_symbol, '
                    'min_topic, min_alphabetic, min_numeric, '
                    'max_topic, max_alphabetic, max_numeric, '
                    'description) VALUES (:class_symbol, :subclass_symbol, '
                    ':min_topic, :min_alphabetic, :min_numeric, '
                    ':max_topic, :max_alphabetic, :max_numeric, '
                    ':description);',
                    topic
                )

    cursor.connection.commit()




def main():
    """
    Run the liblib script.
    """
    parser = ArgumentParser(description="A library management tool")
    parser.add_argument('--database', '-d', default=LIBRARY, type=Path,
                        help="Path to the liblib database")

    subparser = parser.add_subparsers(help="Commands:")

    init_parser = subparser.add_parser('init', help="Initialize a database")
    init_parser.add_argument('--force', '-f', action='store_true',
                             help="Overwrite any existing database")
    init_parser.add_argument('topics_file', type=Path,
                             help="File containing lcc topics")
    init_parser.set_defaults(command='init')

    args = parser.parse_args()

    if args.command == 'init':
        initialize(args.topics_file, location=args.database, force=args.force)
