package eu.dnetlib.functionality.recommendation.app;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;

public class MailHostPreferences {

    private String file; //the full pathname of file
    private String header; //header in file
    //program options that persist
    private Properties defPref = new Properties();   //default values
    private Properties pref = new Properties( defPref ); //user defined values
    static Logger logger = Logger.getLogger( MailHostPreferences.class );
    //initializers

    public MailHostPreferences() {
        /*URL dummyURL = getClass().getResource( "./conf.ini" );
        String path = dummyURL.getPath();
        file = dummyURL.getPath();
        file = file.replaceAll( "%20"," " );
        header = "driver recommendation ini file";*/
        //this.file = ( new File( file ) ).getAbsolutePath(); //convert to absolute path
        //this.header = header;
        setDef();
        pref.clear();
        //load();
    }
    //set default values

    private void setDef() {
        defPref.clear();
        //default values of PSDataFeed class variables
        defPref.put( "mail.smtp.host", "mailhost.di.uoa.gr" ); //the mail server
        defPref.put( "mail.smtp.port", "25" ); //the mail server
    }
    //returns the smtp host name

    String getMailSmtpHost() {
        return ( String ) pref.getProperty( "mail.smtp.host" );
    }

    //restore defaults
    public void restoreDef() {
        pref.clear(); //defPref becomes active
        pref = this.defPref;
        this.store();
    }

    //get and set
    public void setPref( String name, String val ) {
        pref.put( name, val );
    }

    public String getPref( String name ) {
        return pref.getProperty( name ); //null if not there
    }

    public Properties getPref() {
        return pref;
    }

    public String[] getPropertiesAttr() {
    	return pref.stringPropertyNames().toArray(new String[]{});
    }

    //load and save
    public void load() {
        try {
            FileInputStream in = new FileInputStream( file );
            pref.load( in );
        } catch ( IOException e ) {
            //the first time, preferences file will not exist
            restoreDef();
        }
    }

    public void store() {
        try {
            FileOutputStream out = new FileOutputStream( file );
            pref.store( out, header );
        } catch ( IOException e ) {
            logger.debug( "Unable to store user preferences in " + file + ": " + e );
        }
    }
    //it does the same thing as the previous but it does not show a message dialog

    public boolean silentStore() {
        try {
            FileOutputStream out = new FileOutputStream( file );
            pref.store( out, header );
            return true;
        } catch ( IOException e ) {
            return false;
        }
    }
}
