/*
 * 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 } from "../../common/query";

export class DataCtrl {
    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 = [];
        if (req.query.filters) {
            clauses = req.query.filters.split(";").filter((item: string) => item !== "");
        }
        let view;

        try {
            let query: Query = { metrics: [], dimensions: [], clauses: [] };
            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]));
            }
            view = req.engine.query(query);
        }
        catch (e) {
            res.status(500).json({
                message: "Query execution failed: " +
                "Could not construct query with the paramters given.",
                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;
            }

            res.status(200).json(result);
            return;
        });
    }
}