/*
 * Copyright (C) 2018 Centro de Computacao Cientifica e Software Livre
 * Departamento de Informatica - Universidade Federal do Parana
 *
 * This file is part of blend.
 *
 * blend is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * blend is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with blend.  If not, see <http://www.gnu.org/licenses/>.
 */

import { SQLAdapter } from "./sql";
import { View } from "../core/view";
import { Source } from "../core/source";
import { FilterOperator } from "../core/filter";
import { DataType } from "../common/types";
/** @hidden */
const MDB = require("monetdb")();

/**
 * Params required to connect with a MonetDB database and
 * to create a MonetAdapter object.
 */
export interface MonetConfig {
    /** Database hostname */
    host: string;
    /** Database port */
    port: number;
    /** Database name */
    dbname: string;
    /** Database user */
    user: string;
    /** Datavase password */
    password: string;
}
/**
 * Represent the data format returned by MonetDB.
 * This interface is used to parse this format to the BlenDB Standart.
 */
interface MonetResult {
    /** Query result as a list of values */
    data: any[];
    /** Meta data of each attribute required. */
    structure: {type: string, column: string, index: number}[];
}

/**
 * Adapter which connects with a MonetDB database.
 */
export class MonetAdapter extends SQLAdapter {
    /** Information used to connect with a MonetDB database. */
    private config: MonetConfig;

    /**
     * Creates a new adapter with the database connection configuration.
     * @param conf - The information required to create a connection with
     * the database.
     */
    constructor (conf: MonetConfig) {
        super();
        this.config = conf;
    }

    /**
     * Asynchronously reads all data from given view.
     * In other words perform a SELECT query.
     * @param view - "Location" from all data should be read.
     * @param cb - Callback function which contains the data read.
     * @param cb.error - Error information when the method fails.
     * @param cb.result - Data got from view.
     */
    public getDataFromView(view: View, cb: (error: Error, result?: any[]) => void): void {
        const query = this.getQueryFromView(view);
        this.executeQuery(query, cb);
    }

    /**
     * Asynchronously executes a query and get its result.
     * @param query - Query (SQL format) to be executed.
     * @param cb - Callback function which contains the data read.
     * @param cb.error - Error information when the method fails.
     * @param cb.result - Query result.
     */
    private executeQuery(query: string, cb: (error: Error, result?: any[]) => void): void {
        let pool: any = new MDB(this.config);
        pool.connect();
        pool.query(query).then((result: MonetResult) => {
            if (result) {
                let res = result.data.map((item) => {
                    let obj: any = {};
                    for (let i = 0; i < result.structure.length; ++i) {
                        let struct = result.structure[i];
                        if (struct.type === "timestamp") {
                            obj[struct.column] = new Date(item[struct.index]);
                        }
                        else {
                            obj[struct.column] = item[struct.index];
                        }
                    }
                    return obj;
                });
                cb(null, res);
            }
            else {
                cb(null, null);
            }
        }).fail((err: Error) => {
            cb(err, null);
        });
        pool.close();
    }
    /**
     * Asynchronously executes a query from Source and get its resut
     * @param query - Query (SQL format) to be executed.
     * @param cb - Callback function which contains the data read.
     * @param cb.error - Error information when the method fails.
     * @param cb.result - Query result.
     */

    private executeQuerySource(query: string, cb: (error: Error, result?: any[]) => void): void {
        let pool: any = new MDB(this.config);
        pool.connect();
        pool.query(query).then((result: any) => {
            if (result) {
                cb(null, result);
            }
            else {
                cb(null, null);
            }
        }).fail((err: Error) => {
            cb(err, null);
        });
        pool.close();
    }

    /**
     * Asynchronously insert one register into a given Source.
     * @param source - Insertion "location".
     * @param data - Data to be inserted.
     * @param cb - Callback function which contains the query result.
     * @param cb.error - Error information when the method fails.
     * @param cb.result - Query result.
     */
    public insertIntoSource(source: Source, data: any[], cb: (err: Error, result: any[]) =>  void): void {
        const query = this.getQueryFromSource(source, data);
        this.executeQuerySource(query, cb);
    }

    /**
     * Cast BlenDB data types to be used in MonetDB queries.
     * @param quotedValue - SQL query attribute wrapped by quotes.
     * @param dt - Attribute data type.
     */
    protected typeCast(quotedValue: string, dt: DataType): string {
        switch (dt) {
            case DataType.DATE:
                return "CAST(" + quotedValue + " AS TIMESTAMP)";
            case DataType.INTEGER:
                return "CAST(" + quotedValue + " AS INTEGER)";
            case DataType.BOOLEAN:
                return "CAST(" + quotedValue + " AS BOOLEAN)";
            default:
                return quotedValue;
        }
    }

    /**
     * Translate filter operator to be used in MonetDB queries.
     * @param lSide - Operation left side operator.
     * @param rSide - Operation right side operator.
     * @param op - Operation to be performed.
     */
    protected applyOperator(lSide: string, rSide: string, op: FilterOperator): string {
        switch (op) {
            case FilterOperator.EQUAL:
                return lSide + " = " + rSide;
            case FilterOperator.NOTEQUAL:
                return "NOT(" + lSide + " = " + rSide + ")";
            case FilterOperator.GREATER:
                return lSide + " > " + rSide;
            case FilterOperator.LOWER:
                return lSide + " < " + rSide;
            case FilterOperator.GREATEREQ:
                return lSide + " >= " + rSide;
            case FilterOperator.LOWEREQ:
                return lSide + " <= " + rSide;
            default:
                return  "";
        }
    }
}