/*
 * 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.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

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

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;


public class LogSettingsController  implements Controller, ResourceLoaderAware
{
	private static Logger log = Logger.getLogger(LogSettingsController.class);
	
	private Map<String, String> loggers = new LinkedHashMap<String, String>();
	private Map<String, String> loggerDescriptions;
	private List<String> loggerDescriptionFiles = new ArrayList<String>();
    private ResourceLoader resourceLoader;

	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String loggerArg = request.getParameter("logger");
		String levelArg = request.getParameter("level");
		
		initLoggerDescriptions();
		
		if (loggerArg != null && levelArg != null) {
			Logger log = Logger.getLogger(loggerArg);
			log.setLevel(Level.toLevel(levelArg));
			loggers.put(loggerArg, levelArg);
		}
		
		for (String l : loggers.keySet()) {
			Logger log = Logger.getLogger(l);
			Level level = log.getEffectiveLevel();
			loggers.put(l, level.toString());
		}
		ModelAndView mav = new ModelAndView("modules/administer/logSettings");
		mav.addObject("loggers", loggers);
		mav.addObject("loggerDesc", loggerDescriptions);
		return mav;
	}

	/**
	 * 
	 */
	private void initLoggerDescriptions() {
		if (loggerDescriptions != null) {
			return;
		}
		loggerDescriptions = new LinkedHashMap<String, String>();
		if (loggerDescriptionFiles != null) {
			for (String file : loggerDescriptionFiles) {
				try {
					String props = loadWebappFile(file);
					if (props != null) {
						Properties p = new Properties();
						p.load(new ByteArrayInputStream(props.getBytes()));
						for (Object key : p.keySet()) {
							String keyStr = (String) key;
							loggerDescriptions.put(keyStr, p.getProperty(keyStr));
							loggers.put(keyStr, null);
						}
					}
				} catch (IOException e) {
					log.warn("problem loading log descriptions", e);
				}
			}
		}
	}

    /**
     * load a file located somewhere in the webapp
     * @param path
     * @return
     * @throws IOException
     */
    private String loadWebappFile(String path) throws IOException {
        // use resource loader to look up something in servlet context
        org.springframework.core.io.Resource test = resourceLoader.getResource(path);
        InputStream is = test.getInputStream();
        // read it into a string and return it
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int n;
        while ((n = is.read(bytes)) > 0) {
            baos.write(bytes, 0, n);
        }
        return baos.toString();
    }

	/* (non-Javadoc)
	 * @see org.springframework.context.ResourceLoaderAware#setResourceLoader(org.springframework.core.io.ResourceLoader)
	 */
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

	public List<String> getLoggerDescriptionFiles() {
		return loggerDescriptionFiles;
	}

	public void setLoggerDescriptionFiles(List<String> loggerDescriptionFiles) {
		this.loggerDescriptionFiles = loggerDescriptionFiles;
	}
}
