/*
 * Copyright (C) 2005 NTT DATA Corporation
 * 
 */
package org.postgresforest.tool.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.jface.preference.IPreferenceStore;
import org.postgresforest.tool.ForestToolPlugin;
import org.postgresforest.tool.bean.LoginInfo;

/**
 *
 * LoginHistry
 * @version $Revision: 1.1.1.1 $
 * @since 
 */
public class LoginHistry {

    public static final String ADMIN = "login.admin";
    public static final String CHECK = "login.check";

    private static final int HISTRY_COUNT = 10; 
    private static final String DB_NAME = "db_name";
    private static final String HOST_NAME = "host_name";
    private static final String PORT_NUMBER = "port_num";
    private static final String USER_NAME = "user_name";
    
	private String m_type;

    private IPreferenceStore m_pref =  ForestToolPlugin.getDefault().getPreferenceStore();
	private ArrayList m_loginList;
	
	
    /**
     * @param type
     */
    public LoginHistry(String type) {
        super();
        m_type = type;
    }
    public List load() {

        m_loginList = new ArrayList();
        
        for (int i = 0; i < HISTRY_COUNT; i++) {
            LoginInfo login = new LoginInfo();

            login.setDbname(m_pref.getString(m_type + "." + DB_NAME +"." + i));
        	login.setHostname(m_pref.getString(m_type + "." + HOST_NAME + "."+i));
        	login.setPortno(m_pref.getString(m_type + "." + PORT_NUMBER + "."+i));
        	login.setUser(m_pref.getString(m_type + "." + USER_NAME + "."+i));
        	
        	if( !login.getDbname().equals("") &&
        	    !login.getHostname().equals("") &&
        	    !login.getPortno().equals("") &&
        	    !login.getUser().equals("")   ){
        	    m_loginList.add(login);
        	}
        }

        return m_loginList;
    }
    
    public void save(LoginInfo newLogin) {

        //新しいリストの作成
        for (Iterator iter = m_loginList.iterator(); iter.hasNext();) {
            LoginInfo  login = (LoginInfo) iter.next();
            //新しいログイン情報と同じ情報を削除
            if(newLogin.toString().equals(login.toString())){
                m_loginList.remove(login);
                break;
            }
        }
        
        //新しいログイン情報をリストの先頭へセット
        m_loginList.add(0, newLogin);
        
        //履歴の保存
       int i=0;
        for (Iterator iter = m_loginList.iterator(); iter.hasNext();i++) {
            LoginInfo  login = (LoginInfo) iter.next();
            m_pref.putValue(m_type + "." + DB_NAME + "."+i,login.getDbname());
            m_pref.putValue(m_type + "." + HOST_NAME + "."+i,login.getHostname());
            m_pref.putValue(m_type + "." + PORT_NUMBER + "."+i,login.getPortno());
            m_pref.putValue(m_type + "." + USER_NAME + "."+i,login.getUser());
	    }    
    
    }
}
