/*
 * Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
 * 
 * Licensed 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 monasca.api.resource;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;

import com.codahale.metrics.annotation.Timed;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;

import monasca.api.ApiConfig;
import monasca.api.app.MetricService;
import monasca.api.app.command.CreateMetricCommand;
import monasca.api.app.validation.Validation;
import monasca.api.domain.model.metric.MetricDefinitionRepo;
import monasca.api.infrastructure.persistence.PersistUtils;
import monasca.api.resource.exception.Exceptions;
import monasca.common.model.Services;
import monasca.common.model.metric.Metric;

/**
 * Metric resource implementation.
 */
@Path("/v2.0/metrics")
public class MetricResource {

  private static final Splitter COMMA_SPLITTER = Splitter.on(',').omitEmptyStrings().trimResults();

  private final String monitoring_delegate_role;
  private final MetricService service;
  private final MetricDefinitionRepo metricRepo;
  private final PersistUtils persistUtils;

  @Inject
  public MetricResource(ApiConfig config, MetricService service, MetricDefinitionRepo metricRepo,
                        PersistUtils persistUtils) {
    if (config.middleware == null || config.middleware.delegateAuthorizedRole == null) {
      this.monitoring_delegate_role = "monitoring-delegate";
    } else {
      this.monitoring_delegate_role = config.middleware.delegateAuthorizedRole;
    }
    this.service = service;
    this.metricRepo = metricRepo;
    this.persistUtils = persistUtils;
  }

  @POST
  @Timed
  @Consumes(MediaType.APPLICATION_JSON)
  public void create(@Context UriInfo uriInfo, @HeaderParam("X-Tenant-Id") String tenantId,
                     @HeaderParam("X-Roles") String roles,
                     @QueryParam("tenant_id") String crossTenantId,
                     @Valid CreateMetricCommand[] commands) {
    boolean
        isDelegate =
        !Strings.isNullOrEmpty(roles) && COMMA_SPLITTER.splitToList(roles)
            .contains(monitoring_delegate_role);
    List<Metric> metrics = new ArrayList<>(commands.length);
    for (CreateMetricCommand command : commands) {
      if (!isDelegate) {
        if (command.dimensions != null) {
          String service = command.dimensions.get(Services.SERVICE_DIMENSION);
          if (service != null && Services.isReserved(service)) {
            throw Exceptions
                .forbidden("Project %s cannot POST metrics for the hpcs service", tenantId);
          }
        }
        if (!Strings.isNullOrEmpty(crossTenantId) && !crossTenantId.equals(tenantId)) {
          throw Exceptions.forbidden("Project %s cannot POST cross tenant metrics", tenantId);
        }
      }

      command.validate();
      metrics.add(command.toMetric());
    }

    service.create(metrics, tenantId, crossTenantId);
  }

  @GET
  @Timed
  @Produces(MediaType.APPLICATION_JSON)
  public Object getMetrics(@Context UriInfo uriInfo, @HeaderParam("X-Tenant-Id") String tenantId,
                           @QueryParam("name") String name,
                           @QueryParam("dimensions") String dimensionsStr,
                           @QueryParam("offset") String offset,
                           @QueryParam("limit") String limit)
      throws Exception {
    Map<String, String>
        dimensions =
        Strings.isNullOrEmpty(dimensionsStr) ? null : Validation
            .parseAndValidateNameAndDimensions(name, dimensionsStr, false);

    return Links.paginate(this.persistUtils.getLimit(limit),
                          metricRepo.find(tenantId, name, dimensions, offset, this.persistUtils.getLimit(limit)), uriInfo);
  }

  @GET
  @Path("/names")
  @Timed
  @Produces(MediaType.APPLICATION_JSON)
  public Object getMetricNames(@Context UriInfo uriInfo,
                               @HeaderParam("X-Tenant-Id") String tenantId,
                               @QueryParam("dimensions") String dimensionsStr,
                               @QueryParam("offset") String offset,
                               @QueryParam("limit") String limit) throws Exception {
    Map<String, String>
        dimensions =
        Strings.isNullOrEmpty(dimensionsStr) ? null : Validation
            .parseAndValidateDimensions(dimensionsStr);

    return Links.paginate(this.persistUtils.getLimit(limit),
                          metricRepo.findNames(tenantId, dimensions, offset, this.persistUtils.getLimit(limit)), uriInfo);
  }
}

@@ -1323,16 +1323,72 @@
 ommand;%0A
+import monasca.api.app.validation.MetricNameValidation;%0A
 import m
@@ -4303,32 +4303,34 @@
 Exception %7B%0A    
+  
 Map%3CString, Stri
@@ -4328,32 +4328,24 @@
 ing, String%3E
-%0A       
  dimensions 
@@ -4341,32 +4341,43 @@
 dimensions =
+ null;%0A
 %0A      
- 
+if (!
  Strings.isN
@@ -4405,41 +4405,43 @@
 Str)
- ? null : Validation%0A            
+) %7B%0A        dimensions = Validation
 .par
@@ -4499,16 +4499,132 @@
  false);
+%0A      %7D else if (! Strings.isNullOrEmpty(name)) %7B%0A        MetricNameValidation.validate(name, null, false);%0A      %7D
 %0A%0A    re

Validate metric name if dimensionstr is not present