/*
 * Copyright 2000-2013 JetBrains s.r.o.
 *
 * 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 jetbrains.buildServer.web.eclipse;

import jetbrains.buildServer.controllers.BaseController;
import jetbrains.buildServer.controllers.HttpDownloadProcessor;
import jetbrains.buildServer.web.openapi.PluginDescriptor;
import jetbrains.buildServer.web.openapi.WebControllerManager;
import jetbrains.buildServer.web.util.WebUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

public class EclipsePluginDownloadController extends BaseController {

  @NotNull
  private final PluginDescriptor myPluginDescriptor;
  @NotNull
  private final WebControllerManager myWebManager;
  @NotNull
  private final File myUpdateSiteRoot;
  @NotNull
  private final HttpDownloadProcessor myDownloadProcessor;


  public EclipsePluginDownloadController(@NotNull PluginDescriptor descriptor, @NotNull WebControllerManager manager, @NotNull HttpDownloadProcessor processor) {
    myPluginDescriptor = descriptor;
    myWebManager = manager;
    myDownloadProcessor = processor;
    myUpdateSiteRoot = new File(myPluginDescriptor.getPluginRoot(), Constants.UPDATE_SITE_DIR_NAME);
  }

  public void register() {
    myWebManager.registerController(Constants.UPDATE_URL, this);
    myWebManager.registerController(Constants.UPDATE_URL + "/**", this);
  }

  @Override
  protected ModelAndView doHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response) throws Exception {
    final String pathWithoutContext = WebUtil.getPathWithoutContext(request);
    if (!pathWithoutContext.startsWith(Constants.UPDATE_URL) || pathWithoutContext.contains("/..")) {
      return notFoundView("Wrong path: " + pathWithoutContext, response);
    }
    final String path = pathWithoutContext.substring(Constants.UPDATE_URL.length());
    final String relative = path.startsWith("/") ? path.substring(1) : path;
    if ("".equals(relative)) {
      // Request from browser, dispatch index.jsp
      final String jsp = myPluginDescriptor.getPluginResourcesPath("index.jsp");
      ModelAndView mv = new ModelAndView(jsp);
      mv.getModel().put("serverBaseUrl", WebUtil.getRootUrl(request));
      mv.getModel().put("eclipseUpdatePath", Constants.UPDATE_URL + "/");
      return mv;
    } else {
      final File result = new File(myUpdateSiteRoot, relative);
      if (!result.isFile()) {
        return notFoundView("Wrong path: " + pathWithoutContext, response);
      }
      return myDownloadProcessor.processFileDownload(result, request, response);
    }
  }

  private ModelAndView notFoundView(@NotNull String message, @NotNull HttpServletResponse response) throws IOException {
    response.sendError(HttpServletResponse.SC_NOT_FOUND, message);
    return null;
  }
}
