/*
 * Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
 * Departamento de Informatica - Universidade Federal do Parana
 *
 * This file is part of blendb.
 *
 * blendb 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.
 *
 * blendb 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 blendb.  If not, see <http://www.gnu.org/licenses/>.
 */

import * as express from "express";
import { Request } from "../types";
import { Query, QueryOpts } from "../../common/query";

/**
 * Constroller responsable for data part from the API. In other
 * words, controller responsable for reading data in BlenDB.
 */
export class DataCtrl {
    /**
     * Route that validates a query and returns the query data.
     * @param req - Object with request information
     * @param res - Object used to create and send the response
     * @param next - Call next middleware or controller. Not used but required
     * by typescript definition of route.
     */
    public static read(req: Request, res: express.Response, next: express.NextFunction) {
        let metrics = req.query.metrics.split(",").filter((item: string) => item !== "");
        let dimensions = req.query.dimensions.split(",").filter((item: string) => item !== "");
        let clauses = [];
        let sort: string[] = [];
        if (req.query.filters) {
            clauses = req.query.filters.split(";").filter((item: string) => item !== "");
        }
        if (req.query.sort) {
            sort = req.query.sort.split(",").filter((item: string) => item !== "");
        }

        let format = "json";
        if (req.query.format) {
            format = req.query.format;
        }

        let view;

        try {
            const qOpt: QueryOpts = { metrics: [], dimensions: []};
            let query = new Query(qOpt);
            for (let i = 0; i < metrics.length; ++i) {
                query.metrics.push(req.engine.getMetricByName(metrics[i]));
            }

            for (let i = 0; i < dimensions.length; ++i) {
                query.dimensions.push(req.engine.getDimensionByName(dimensions[i]));
            }

            for (let i = 0; i < clauses.length; ++i) {
                query.clauses.push(req.engine.parseClause(clauses[i]));
            }

            for (let i = 0; i < sort.length; ++i) {
                const m = query.metrics.find((item) => item.name === sort[i]);
                if (!m) {
                    const d = query.dimensions.find((item) => item.name === sort[i]);
                    if (!d) {
                        throw new Error(
                            "The item '" +  sort[i] +
                            "' is not present in neither metrics nor dimensions list");
                    }
                    else {
                        query.sort.push(d);
                    }
                }

                else {
                    query.sort.push(m);
                }

            }
            view = req.engine.query(query);
        }
        catch (e) {
            res.status(500).json({
                message: "Query execution failed: " +
                "Could not construct query with the given parameters.",
                error: e.message
             });
            return;
        }

        req.adapter.getDataFromView(view, (err: Error, result: any[]) => {
            if (err) {
                res.status(500).json({
                    message: "Query execution failed " +
                    "failed on execute query on database.",
                    error: err
                 });
                return;
            }

            if (format === "json") {
                res.status(200).json(result);
            }

            else {
                req.csvParser(result, format, (error: Error, csv: string) => {
                    if (error) {
                        res.status(500).json({
                            message: "Error generating csv file. " +
                            "Try json format.",
                            error: error
                        });
                        return;
                    }

                    res.setHeader("Content-Type", "text/csv");
                    res.setHeader("Content-disposition", "attachment;filename=data.csv");
                    res.status(200).send(csv);
                });
            }
            return;
        });
    }
}