/*
 * Copyright (C) 2005 - 2011 Jaspersoft Corporation. All rights reserved.
 * http://www.jaspersoft.com.
 *
 * Unless you have purchased  a commercial license agreement from Jaspersoft,
 * the following license terms  apply:
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License  as
 * published by the Free Software Foundation, either version 3 of  the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero  General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public  License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.jaspersoft.jasperserver.war.control;


import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.context.SecurityContextHolder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.servlet.ModelAndView;

import com.jaspersoft.jasperserver.api.common.util.TimeZonesList;
import com.jaspersoft.jasperserver.api.metadata.user.service.impl.UserAuthorityServiceImpl;
import com.jaspersoft.jasperserver.war.common.HeartbeatBean;
import com.jaspersoft.jasperserver.war.common.HeartbeatClientInfo;
import com.jaspersoft.jasperserver.war.common.JasperServerConstImpl;
import com.jaspersoft.jasperserver.war.common.LocalesList;


/**
 * @author aztec
 * @version $Id: JSCommonController.java 20336 2011-04-08 13:09:18Z yuriy.plakosh $
 */
public class JSCommonController extends JRBaseMultiActionController {

	protected HeartbeatBean heartbeat;

	private LocalesList locales;
	private TimeZonesList timezones;
	private String allowUserPasswordChange;
	private String passwordExpirationInDays;
    private static final String LICENSE_MANAGER = "com.jaspersoft.ji.license.LicenseManager";

	private static Log log = LogFactory.getLog(JSCommonController.class);

	/*
	 * Overridden method for handling the requests
	 * @args HttpServletRequest, HttpServletResponse
	 * @returns ModelAndView - Home Page
	 */
	public ModelAndView homePage(HttpServletRequest req, HttpServletResponse res)
			throws ServletException {
		return new ModelAndView("modules/home");
	}

    public ModelAndView login(HttpServletRequest req, HttpServletResponse res)
            throws ServletException {
        setupLoginPage(req);

        return new ModelAndView("modules/login/login");
    }

    protected void setupLoginPage(HttpServletRequest req) {
        Cookie[] cookies = req.getCookies();
        String locale = null;
        String preferredTz = null;
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals(JasperServerConstImpl.getUserLocaleSessionAttr()))
                    locale = cookie.getValue();
                if (cookie.getName().equals(JasperServerConstImpl.getUserTimezoneSessionAttr()))
                    preferredTz = cookie.getValue();
            }
        }

        Locale displayLocale = req.getLocale();
        String preferredLocale;
        if (locale == null || locale.length() == 0) {
            preferredLocale = displayLocale.toString();
        } else {
            preferredLocale = locale;
        }

        if (preferredTz == null) {
            preferredTz = timezones.getDefaultTimeZoneID();
        }

        req.setAttribute("preferredLocale", preferredLocale);
        req.setAttribute("userLocales", locales.getUserLocales(displayLocale));
        req.setAttribute("preferredTimezone", preferredTz);
        req.setAttribute("userTimezones", timezones.getTimeZones(displayLocale));
        try {
            if (Integer.parseInt(passwordExpirationInDays) > 0) {
                allowUserPasswordChange = "true";
            }
        } catch (NumberFormatException e) {
            // if the value is NaN, then assume it's non postive.
            // not overwrite allowUserPasswordChange
        }
        req.setAttribute("allowUserPasswordChange", allowUserPasswordChange);
        req.setAttribute("passwordExpirationInDays", passwordExpirationInDays);
        req.setAttribute("usersExceeded", usersExceeded());
        req.setAttribute("banUser", banUser());
    }

    public ModelAndView heartbeat(HttpServletRequest req, HttpServletResponse res) throws ServletException {
        boolean isCallPermitted = false;

        String permit = req.getParameter("permit");
        if (permit != null) {
            isCallPermitted = Boolean.valueOf(permit);
        }

        heartbeat.permitCall(isCallPermitted);

        return new ModelAndView("ajax/ajaxresponse");
    }

    public ModelAndView heartbeatInfo(HttpServletRequest req, HttpServletResponse res) throws ServletException {
        final HeartbeatClientInfo info = new HeartbeatClientInfo();

        info.setNavigatorAppName(req.getParameter("navAppName"));
        info.setNavigatorAppVersion(req.getParameter("navAppVersion"));
        info.setNavigatorLocale(req.getLocale());
        info.setUserLocale(LocaleContextHolder.getLocale());
        if (req.getParameter("scrWidth") != null) {
            info.setScreenWidth(new Integer(req.getParameter("scrWidth")));
        }
        if (req.getParameter("scrHeight") != null) {
            info.setScreenHeight(new Integer(req.getParameter("scrHeight")));
        }
        if (req.getParameter("scrColorDepth") != null) {
            info.setScreenColorDepth(new Integer(req.getParameter("scrColorDepth")));
        }
        info.setUserAgent(req.getHeader("user-agent"));

        new Thread(
                new Runnable() {
                    public void run() {
                        heartbeat.updateClientInfo(info);
                    }
                }
        ).start();

        return new ModelAndView("ajax/ajaxresponse");
    }


    public ModelAndView exitUser(HttpServletRequest req, HttpServletResponse res) {
	String redirectURL = "/logout.html" + "?" + "showPasswordChange="+req.getParameter("showPasswordChange");
	if (UserAuthorityServiceImpl.isUserSwitched()) {
	    redirectURL = "/j_acegi_exit_user";
	}
	return new ModelAndView("redirect:" + redirectURL);
    }

	public ModelAndView logout(HttpServletRequest req, HttpServletResponse res)
			throws ServletException {
		// invalidate session
		HttpSession session = req.getSession(false);
		if (session != null) {
			session.invalidate();
		}
		// we aren't using RememberMe but this is how we'd log out if we did
		// Cookie terminate = new Cookie(TokenBasedRememberMeServices.ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE_KEY, null);
		// terminate.setMaxAge(0);
		// res.addCookie(terminate);
		SecurityContextHolder.clearContext(); //invalidate authentication
		return new ModelAndView("redirect:/login.html" + "?" + "showPasswordChange="+req.getParameter("showPasswordChange"));
	}

	public ModelAndView loginError(HttpServletRequest req, HttpServletResponse res)
		throws ServletException {
		log.warn("There was a login error");
		return new ModelAndView("modules/loginError");
	}

	/*
	 * @args req, res
	 * @returns ModelAndView - menutest.jsp
	 */
	public ModelAndView menuTest(HttpServletRequest req, HttpServletResponse res)
			throws ServletException {
		return new ModelAndView("menutest");
	}

    /**
     * Helper method to determine if we are running the Pro or Enterprise edition
     * @return boolean indicating success..
     */
    public boolean isProVersion(){
        boolean isPro = false;
        try {
            Class clazz = Class.forName(LICENSE_MANAGER);
            if(clazz != null){
                isPro = true;
            }
        } catch (ClassNotFoundException e) {
            if(log.isDebugEnabled()){
                log.info("This is not a pro version. Access is denied");
            }
        }
        return isPro;
    }

    public boolean usersExceeded(){
        boolean exceeded = false;
        if(isProVersion()){
            try {
                Class clazz = Class.forName(LICENSE_MANAGER);
                Method method = clazz.getDeclaredMethod("checkUsers");
                exceeded  = ((Boolean) method.invoke(method.getDeclaringClass())).booleanValue();
            } catch (Exception e) {
                if(log.isDebugEnabled()){
                    log.info("This is not a pro version. Access is denied");
                }
            }
        }
        return exceeded;
    }

    public boolean banUser(){
        boolean banUser = false;
        if(isProVersion()){
            try {
                Class clazz = Class.forName(LICENSE_MANAGER);
                Method method = clazz.getDeclaredMethod("banUserRole");
                banUser  = ((Boolean) method.invoke(method.getDeclaringClass())).booleanValue();
            } catch (Exception e) {
                if(log.isDebugEnabled()){
                    log.info("This is not a pro version. Access is denied");
                }
            }
        }
        return banUser;
    }

	public LocalesList getLocales()
	{
		return locales;
	}

	public void setLocales(LocalesList locales)
	{
		this.locales = locales;
	}

	public TimeZonesList getTimezones()
	{
		return timezones;
	}

	public void setTimezones(TimeZonesList timezones)
	{
		this.timezones = timezones;
	}

	public String getAllowUserPasswordChange()
	{
		return allowUserPasswordChange;
	}

	public void setAllowUserPasswordChange(String changePassword)
	{
		this.allowUserPasswordChange = changePassword;
	}

	public String getPasswordExpirationInDays() {
		return passwordExpirationInDays;
	}

	public void setPasswordExpirationInDays(String passwordExpirationInDays) {
		this.passwordExpirationInDays = passwordExpirationInDays;
	}
	
	public HeartbeatBean getHeartbeat() {
		return heartbeat;
	}

	public void setHeartbeat(HeartbeatBean heartbeat) {
		this.heartbeat = heartbeat;
	}
	
	
}
