/*
 * Copyright (c) 2015 Spotify AB.
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package com.spotify.heroic.http.render;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.inject.Named;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.jfree.chart.JFreeChart;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.spotify.heroic.Query;
import com.spotify.heroic.QueryBuilder;
import com.spotify.heroic.QueryManager;
import com.spotify.heroic.http.query.QueryMetrics;
import com.spotify.heroic.metric.QueryResult;

@Path("render")
public class RenderResource {
    private static final int DEFAULT_WIDTH = 600;

    private static final int DEFAULT_HEIGHT = 400;

    @Inject
    @Named(MediaType.APPLICATION_JSON)
    private ObjectMapper mapper;

    @Inject
    private QueryManager query;

    @SuppressWarnings("unchecked")
    @GET
    @Path("image")
    @Produces("image/png")
    public Response render(@QueryParam("query") String query, @QueryParam("backend") String backendGroup,
            @QueryParam("title") String title, @QueryParam("width") Integer width,
            @QueryParam("height") Integer height, @QueryParam("highlight") String highlightRaw,
            @QueryParam("threshold") Double threshold) throws Exception {
        if (query == null) {
            throw new BadRequestException("'query' must be defined");
        }

        if (width == null) {
            width = DEFAULT_WIDTH;
        }

        if (height == null) {
            height = DEFAULT_HEIGHT;
        }

        final Map<String, String> highlight;

        if (highlightRaw != null) {
            highlight = mapper.readValue(highlightRaw, Map.class);
        } else {
            highlight = null;
        }

        final QueryMetrics queryMetrics = mapper.readValue(query, QueryMetrics.class);
        final Query q = setupBuilder(queryMetrics).build();

        final QueryResult result = this.query.useGroup(backendGroup).query(q).get();

        final JFreeChart chart = RenderUtils.createChart(result.getGroups(), title, highlight, threshold, height);

        final BufferedImage image = chart.createBufferedImage(width, height);

        final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ImageIO.write(image, "png", buffer);

        return Response.ok(buffer.toByteArray()).build();
    }

    @SuppressWarnings("deprecation")
    private QueryBuilder setupBuilder(final QueryMetrics q) {
        return q.getQuery().transform(query::newQueryFromString).or(() -> {
            return query.newQuery().key(q.getKey()).tags(q.getTags()).groupBy(q.getGroupBy()).filter(q.getFilter())
                    .range(Optional.of(q.getRange().buildDateRange())).disableCache(q.isNoCache())
                    .aggregationQuery(q.getAggregators()).source(q.getSource());
        });
    }
}

@@ -1346,48 +1346,8 @@
 er;%0A
-import com.google.common.base.Optional;%0A
 impo
@@ -1443,106 +1443,15 @@
 uery
-Builder;%0Aimport com.spotify.heroic.QueryManager;%0Aimport com.spotify.heroic.http.query.QueryMetrics
+Manager
 ;%0Aim
@@ -1905,20 +1905,16 @@
 Param(%22q
-uery
 %22) Strin
@@ -1920,16 +1920,22 @@
 ng query
+String
 , @Query
@@ -2718,125 +2718,49 @@
 uery
-Metrics queryMetrics = mapper.readValue(query, QueryMetrics.class);%0A        final Query q = setupBuilder
+ q = query.newQueryFromString
 (query
-Metrics
+String
 ).bu
@@ -3236,496 +3236,5 @@
   %7D%0A
-%0A    @SuppressWarnings(%22deprecation%22)%0A    private QueryBuilder setupBuilder(final QueryMetrics q) %7B%0A        return q.getQuery().transform(query::newQueryFromString).or(() -%3E %7B%0A            return query.newQuery().key(q.getKey()).tags(q.getTags()).groupBy(q.getGroupBy()).filter(q.getFilter())%0A                    .range(Optional.of(q.getRange().buildDateRange())).disableCache(q.isNoCache())%0A                    .aggregationQuery(q.getAggregators()).source(q.getSource());%0A        %7D);%0A    %7D%0A%7D%0A
+%7D

use string queries for render resource