/*
 * 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 { Pool, PoolConfig } from "pg";
import { DataType } from "../common/types";

/** Adapter which connects with a PostgreSQL database. */
export class PostgresAdapter extends SQLAdapter {
    /** Information used to connect with a PostgreSQL database. */
    private pool: Pool;

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

    /**
     * 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: (err: Error, result?: any[]) =>  void): void{
        this.pool.connect((err, client, done) => {
            if (err) {
                cb (err);
                return;
            }
            client.query(query, [], (error, result) => {
                // call 'done()' to release client back to pool
                done();
                cb(error, (result) ? result.rows : null);
            });
        });
    }

    /**
     * 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.executeQuery(query, cb);
    }

    /**
     * Cast BlenDB data types to be used in PostgreSQL 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 quotedValue + "::DATE";
            case DataType.INTEGER:
                return quotedValue + "::INTEGER";
            case DataType.BOOLEAN:
                return quotedValue + "::BOOLEAN";
            default:
                return quotedValue;
        }
    }

    /**
     * Translate filter operator to be used in PostgreSQL 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 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  "";
        }
    }
}