/*******************************************************************************
 * Copyright 2019 2Fi Business Solutions Ltd.
 *
 *
 *
 * This code is copyrighted. Under no circumstances should any party, people,
 * or organization should redistribute any portions of this code in any form,
 * either verbatim or through electronic media, to any third parties, unless
 * under explicit written permission by 2Fi Business Solutions Ltd.
 ******************************************************************************/
package com.ffii.tbms.sjs.web;

import java.util.Arrays;
import java.util.List;

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

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ffii.core.utils.StringUtils;
import com.ffii.core.web.AbstractController;
import com.ffii.core.web.view.AbstractView;

/**
 * System JS Controller
 */
@Controller
@RequestMapping(value = "/sjs")
public class SjsController extends AbstractController {

	private static final List<String> PATHS = Arrays.asList("controller", "store", "view");
	private static final List<String> PATHS2 = Arrays.asList("combo", "widget", "report");

	@RequestMapping(value = "/{path}/{name}", method = RequestMethod.GET)
	public String js(HttpServletRequest request, HttpServletResponse response, @PathVariable String path, @PathVariable String name)
			throws Exception {

		if (PATHS.contains(path) && StringUtils.endsWith(name, ".js")) {
			response.setContentType(AbstractView.CONTENT_TYPE_JAVASCRIPT);
			return String.format("sjs/%s/%s", path, name);
		} else {
			response.setStatus(HttpServletResponse.SC_NOT_FOUND);
			return null;
		}
	}

	@RequestMapping(value = "/{path}/{path2}/{name}", method = RequestMethod.GET)
	public String widgetJs(HttpServletRequest request, HttpServletResponse response, @PathVariable String path,
			@PathVariable String path2, @PathVariable String name)
			throws Exception {

		if (PATHS.contains(path) && PATHS2.contains(path2) && StringUtils.endsWith(name, ".js")) {
			response.setContentType(AbstractView.CONTENT_TYPE_JAVASCRIPT);
			return String.format("sjs/%s/%s/%s", path, path2, name);
		} else {
			response.setStatus(HttpServletResponse.SC_NOT_FOUND);
			return null;
		}
	}
}
