/*
 * Authentification.java, 22 mai 2006
 * 
 * This file is part of FilmZ.
 *
 * Copyright © 2006 Johan Cwiklinski
 *
 * File :               Authentification.java
 * Author's email :     johan@x-tnd.be
 * Author's Website :   http://www.x-tnd.be/
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 * 
 */

package be.xtnd.films;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.Logger;

import be.xtnd.commons.db.Database;
import be.xtnd.gui.FilmzMain;


/**
 * 
 * @author Johan Cwiklinski
 *
 */
public class Authentification {
	static Logger logger = Logger.getLogger(Authentification.class.getName());
	private static Database database;
	/** */
	public static final String TABLE = "users";

	/**
	 * 
	 * @param ident
	 * @param passe
	 * @return boolean
	 */
	public static boolean connect(String ident, String passe){
		boolean logged = false;
		database = FilmzMain.db;
		String query = "SELECT * FROM " + TABLE + " WHERE login='" + ident + "' AND password='" + encode(passe) + "' AND auth=1";

		try {
			ResultSet rs = database.execQuery(query);
			rs.last();
			if(rs.getRow() == 1){
				logged = true;
				updateLogDate(ident);
			}
			
		} catch (SQLException e) {
			logger.fatal("SQLException while connecting user : "+e.getMessage()+" (code "+e.getErrorCode()+")");
		}
		
		return logged;
	}
	
	private static void updateLogDate(String id) throws SQLException{
		Date d = Calendar.getInstance().getTime();
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		StringBuffer query = new StringBuffer();
		query.append("UPDATE " + TABLE + " SET last_connect=");
		query.append("'" + dateFormat.format(d) + "'");
		query.append(" WHERE login='" + id +"'");
		
		database.execUpdate(query.toString());
	}
		
	private static String encode (String key) {
		byte[] uniqueKey = key.getBytes();
		byte[] hash = null;

		try { //on récupère un objet qui permettra de crypter la chaine
			hash = MessageDigest.getInstance("MD5").digest(uniqueKey);
		}catch (NoSuchAlgorithmException e) {
			throw new Error("no MD5 support in this VM");
		}

		StringBuffer hashString = new StringBuffer();

		for (int i = 0; i < hash.length; ++i) {
			String hex = Integer.toHexString(hash[i]);
			if (hex.length() == 1) {
				hashString.append('0');
				hashString.append(hex.charAt(hex.length() - 1));
			}else {
				hashString.append(hex.substring(hex.length() - 2));
			}
		}

		return hashString.toString();
	}

	
}
