/*
 * 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 org.apache.shindig.gadgets.servlet;

import com.google.common.collect.ImmutableSet;

import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.apache.shindig.common.JsonSerializer;
import org.apache.shindig.common.servlet.HttpUtil;
import org.apache.shindig.common.servlet.InjectedServlet;
import org.apache.shindig.config.ContainerConfig;
import org.apache.shindig.gadgets.GadgetContext;
import org.apache.shindig.gadgets.RenderingContext;
import org.apache.shindig.gadgets.UrlGenerator;
import org.apache.shindig.gadgets.UrlValidationStatus;
import org.apache.shindig.gadgets.features.FeatureRegistry;
import org.apache.shindig.gadgets.features.FeatureResource;

import com.google.inject.Inject;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Simple servlet serving up JavaScript files by their registered aliases.
 * Used by type=URL gadgets in loading JavaScript resources.
 */
public class JsServlet extends InjectedServlet {

  private FeatureRegistry registry;
  @Inject
  public void setRegistry(FeatureRegistry registry) {
    this.registry = registry;
  }
  
  private UrlGenerator urlGenerator;
  @Inject
  public void setUrlGenerator(UrlGenerator urlGenerator) {
    this.urlGenerator = urlGenerator;
  }

  private ContainerConfig containerConfig;
  @Inject
  public void setContainerConfig(ContainerConfig containerConfig) {
    this.containerConfig = containerConfig;
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
    // If an If-Modified-Since header is ever provided, we always say
    // not modified. This is because when there actually is a change,
    // cache busting should occur.
    UrlValidationStatus vstatus = urlGenerator.validateJsUrl(
        req.getRequestURL().append('?').append(req.getQueryString()).toString());
    if (req.getHeader("If-Modified-Since") != null &&
        vstatus == UrlValidationStatus.VALID_VERSIONED) {
      resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
      return;
    }

    // Use the last component as filename; prefix is ignored
    String uri = req.getRequestURI();
    // We only want the file name part. There will always be at least 1 slash
    // (the server root), so this is always safe.
    String resourceName = uri.substring(uri.lastIndexOf('/') + 1);
    if (resourceName.endsWith(".js")) {
      // Lop off the suffix for lookup purposes
      resourceName = resourceName.substring(
          0, resourceName.length() - ".js".length());
    }

    Set<String> needed = ImmutableSet.of(StringUtils.split(resourceName, ':'));

    String debugStr = req.getParameter("debug");
    String containerParam = req.getParameter("container");
    String containerStr = req.getParameter("c");

    boolean debug = "1".equals(debugStr);
    final RenderingContext context = "1".equals(containerStr) ?
        RenderingContext.CONTAINER : RenderingContext.GADGET;
    final String container = 
        containerParam != null ? containerParam : ContainerConfig.DEFAULT_CONTAINER;

    GadgetContext ctx = new GadgetContext() {
      @Override
      public RenderingContext getRenderingContext() {
        return context;
      }
      
      @Override
      public String getContainer() {
        return container;
      }
    };

    Collection<? extends FeatureResource> resources = registry.getFeatureResources(ctx, needed, null);
    StringBuilder jsData = new StringBuilder();
    boolean isProxyCacheable = true;
    for (FeatureResource featureResource : resources) {
      String content = debug ? featureResource.getDebugContent() : featureResource.getContent();
      if (!featureResource.isExternal()) {
        jsData.append(content);
      } else {
        // Support external/type=url feature serving through document.write()
        jsData.append("document.write('<script src=\"").append(content).append("\"></script>')");
      }
      isProxyCacheable = isProxyCacheable && featureResource.isProxyCacheable();
      jsData.append(";\n");
    }

    if (context == RenderingContext.CONTAINER) {
      // Append some container specific things

      Map<String, Object> features = containerConfig.getMap(ctx.getContainer(), "gadgets.features");
      Map<String, Object> config = Maps.newHashMapWithExpectedSize(features == null ? 2 : features.size() + 2);

      if (features != null) {
        // Discard what we don't care about.
        for (String name : registry.getFeatures(needed)) {
          Object conf = features.get(name);
          if (conf != null) {
            config.put(name, conf);
          }
        }
        jsData.append("gadgets.config.init(").append(JsonSerializer.serialize(config)).append(");\n");
      }
    }
    
    if (jsData.length() == 0) {
      resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    switch (vstatus) {
      case VALID_VERSIONED:
        // Versioned files get cached indefinitely
        HttpUtil.setCachingHeaders(resp, !isProxyCacheable);
        break;
      case VALID_UNVERSIONED:
        // Unversioned files get cached for 1 hour.
        HttpUtil.setCachingHeaders(resp, 60 * 60, !isProxyCacheable);
        break;
      case INVALID:
        // URL is invalid in some way, likely version mismatch.
        // Indicate no-cache forcing subsequent requests to regenerate URLs.
        HttpUtil.setNoCache(resp);
        break;
    }
    resp.setContentType("text/javascript; charset=utf-8");
    byte[] response = jsData.toString().getBytes("UTF-8");
    resp.setContentLength(response.length);
    resp.getOutputStream().write(response);
  }
}

@@ -972,16 +972,69 @@
 gUtils;%0A
+import org.apache.shindig.auth.SecurityTokenDecoder;%0A
 import o
@@ -2438,16 +2438,179 @@
 g;%0A  %7D%0A%0A
+  private SecurityTokenDecoder tokenCodec;%0A  @Inject%0A  public void setSecurityTokenCodec(SecurityTokenDecoder tokenCodec) %7B%0A    this.tokenCodec = tokenCodec;%0A  %7D%0A%0A
   @Overr
@@ -5278,46 +5278,29 @@
  // 
-Append some container specific things%0A
+Inject container data
 %0A   

add securitytoken decoder here