# -*- coding: utf-8 -*-

from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import

import os
import codecs
import arff
import argparse
import locale

import scripts_common
from dataset import FileDataset, DbDataset

# import pycharm_remote_debug



def parse_args():
    parser = argparse.ArgumentParser(description='Compose the dataset file')
    parser.add_argument("--name", metavar="STRING",
                        help="Dataset name")
    parser.add_argument("--file", metavar="PATH",
                        help="Read from file")
    parser.add_argument("--connection", metavar="PATH",
                        help="Read from database.(Provide the connection file)")
    parser.add_argument("--database", metavar="NAME",
                        help="Use this database to read dumped information")

    parser.add_argument("--logconnection", metavar="PATH",
                        help="Log in this server.(Provide the connection file)")
    parser.add_argument("--logdatabase", metavar="NAME",
                        help="Use this database to log")
    parser.add_argument("--logcollection", metavar="NAME",
                        help="Use this collection to log")

    args = parser.parse_args()
    scripts_common.inject_json(args, "connection")
    scripts_common.inject_json(args, "logconnection")
    return args



def run(args):
    logger = scripts_common.create_logger(args, "consolidate_dataset")

    try:
        dataset = DbDataset(host=args.connection.host, port=args.connection.port,
                            database=args.database,
                            username=args.connection.username, password=args.connection.password,
                            auth_source=args.connection.auth_source)
        dataset.create_indexes()
        logger.info("Saving to: " + args.name)
        save_to_arff(dataset, args.name, args.file)
        logger.info("All done")
        return 0
    except Exception as e:
        import traceback
        traceback.print_exc()  # file=sys.stdout)
        cls_name = e.__class__.__name__.decode(locale.getpreferredencoding())
        message = e.message.decode(locale.getpreferredencoding())
        logger.fatal(cls_name + ": " + message)
        return 2


def save_to_arff(dataset, dataset_name, file_path):
        with codecs.open(file_path, "wb", encoding="utf-8") as fd:
            obj = {
                "relation": dataset_name,
                "description": "",
                "attributes": attributes_to_arff(dataset),
                "data": hits_to_arff(dataset)
            }
            arff.dump(obj, fd)


def attributes_to_arff(dataset):
    for a in dataset.attributes:
        yield unicode(a), ("_", "X")
    yield "returns", ("yes", "no")
    yield "name", "STRING"


def hits_to_arff(dataset):
    attrs_amount = dataset.attributes_len()
    for name, hits, classification in dataset.individuals:
        row = ["_"] * attrs_amount
        for p in hits:
            row[p] = "X"
        row.append("yes" if classification else "no")
        row.append(name)
        yield row

if __name__ == "__main__":
    # import timeit
    # start_time = timeit.default_timer()
    r = run(parse_args())
    # stop_time = timeit.default_timer()
    # elapsed_time = stop_time - start_time
    # m, s = divmod(elapsed_time, 60)
    # h, m = divmod(m, 60)
    # print("Running time: {:02}:{:02}:{:02} ({})".format(int(h), int(m), int(s), elapsed_time))
    exit(r)
