/**
 * Copyright (C) 2019 Patrik Dufresne Service Logiciel <info@patrikdufresne.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package com.planimod.ui;

import java.util.Properties;
import javax.net.ssl.ManagerFactoryParameters;
import org.eclipse.core.commands.common.EventManager;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceStore;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.util.SafeRunnable;
import com.patrikdufresne.managers.IManagerObserver;
import com.patrikdufresne.managers.ManagerEvent;
import com.patrikdufresne.managers.ManagerException;
import com.planimod.core.ApplicationSetting;
import com.planimod.core.ApplicationSettingManager;
import com.planimod.core.PlanimodManagers;

/**
 * This implementation of of the {@link PreferenceStore} replace the persistence functions to load and save the data
 * using the {@link ApplicationSettingManager}
 * 
 * @author Patrik Dufresne
 */
public class ApplicationSettingPreferenceStore extends EventManager implements IPreferenceStore {

    private IManagerObserver observer = new IManagerObserver() {

        @Override
        public void handleManagerEvent(ManagerEvent event) {
            if (!ApplicationSetting.class.equals(event.clazz)) {
                return;
            }
            for (Object o : event.objects) {
                ApplicationSetting entry = (ApplicationSetting) o;
                // Fire property change
                firePropertyChangeEvent(entry.getName(), null, entry.getName());
            }
        }
    };

    /**
     * Application setting.
     */
    private ApplicationSettingManager setting;

    /**
     * Create a new preference store from the managers.
     * 
     * @param managers
     *            the managers.
     * @throws ManagerException
     *             in case of error querying the database.
     */
    public ApplicationSettingPreferenceStore(PlanimodManagers managers) throws ManagerException {
        if (managers == null) {
            throw new IllegalArgumentException();
        }
        this.setting = managers.getApplicationSettingManager();
    }

    /**
     * Add a listener.
     */
    @Override
    public void addPropertyChangeListener(IPropertyChangeListener listener) {
        if (isListenerAttached()) {
            addListenerObject(listener);
            startListening();
        } else {
            addListenerObject(listener);
        }
    }

    @Override
    public boolean contains(String name) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) {
        final Object[] finalListeners = getListeners();
        // Do we need to fire an event.
        if (finalListeners.length > 0 && (oldValue == null || !oldValue.equals(newValue))) {
            final PropertyChangeEvent pe = new PropertyChangeEvent(this, name, oldValue, newValue);
            for (int i = 0; i < finalListeners.length; ++i) {
                final IPropertyChangeListener l = (IPropertyChangeListener) finalListeners[i];
                SafeRunnable.run(new SafeRunnable(JFaceResources.getString("PreferenceStore.changeError")) {
                    public void run() {
                        l.propertyChange(pe);
                    }
                });
            }
        }
    }

    /**
     * This implementation get the value from the cached properties.
     */
    @Override
    public boolean getBoolean(String name) {
        String value = get(name);
        if (value == null) {
            return BOOLEAN_DEFAULT_DEFAULT;
        }
        if (value.equals(IPreferenceStore.TRUE)) {
            return true;
        }
        return false;
    }

    /**
     * Get the value for the given name either from the local cache or from the manager.
     * 
     * @param name
     * @return
     */
    protected String get(String name) {
        // Get the value from the cache properties. If the value is not
        // available, the default value is define by ApplicationSettingManager.
        try {
            return this.setting.getByName(name);
        } catch (ManagerException e) {
            PlanimodPolicy.showException(e);
            return null;
        }
    }

    /**
     * This implementation always return false.
     */
    @Override
    public boolean getDefaultBoolean(String name) {
        return false;
    }

    /**
     * This implementation always return 0.
     */
    @Override
    public double getDefaultDouble(String name) {
        return 0;
    }

    /**
     * This implementation always return 0.
     */
    @Override
    public float getDefaultFloat(String name) {
        return 0;
    }

    /**
     * This implementation always return 0.
     */
    @Override
    public int getDefaultInt(String name) {
        return 0;
    }

    /**
     * This implementation always return 0.
     */
    @Override
    public long getDefaultLong(String name) {
        return 0;
    }

    /**
     * This implementation return an empty string.
     */
    @Override
    public String getDefaultString(String name) {
        return "";
    }

    /**
     * This implementation get the value from the cached properties.
     */
    @Override
    public double getDouble(String name) {
        String value = get(name);
        if (value == null) {
            return DOUBLE_DEFAULT_DEFAULT;
        }
        double ival = DOUBLE_DEFAULT_DEFAULT;
        try {
            ival = new Double(value).doubleValue();
        } catch (NumberFormatException e) {
            // Swallow
        }
        return ival;
    }

    @Override
    public float getFloat(String name) {
        String value = get(name);
        if (value == null) {
            return FLOAT_DEFAULT_DEFAULT;
        }
        float ival = FLOAT_DEFAULT_DEFAULT;
        try {
            ival = new Float(value).floatValue();
        } catch (NumberFormatException e) {
            // Swallow
        }
        return ival;
    }

    @Override
    public int getInt(String name) {
        String value = get(name);
        if (value == null) {
            return INT_DEFAULT_DEFAULT;
        }
        int ival = 0;
        try {
            ival = Integer.parseInt(value);
        } catch (NumberFormatException e) {
            // Swallow
        }
        return ival;
    }

    @Override
    public long getLong(String name) {
        String value = get(name);
        if (value == null) {
            return LONG_DEFAULT_DEFAULT;
        }
        long ival = LONG_DEFAULT_DEFAULT;
        try {
            ival = Long.parseLong(value);
        } catch (NumberFormatException e) {
            // Swallow
        }
        return ival;
    }

    @Override
    public String getString(String name) {
        String value = get(name);
        if (value == null) {
            return STRING_DEFAULT_DEFAULT;
        }
        return value;
    }

    /**
     * This implementation always return false.
     */
    @Override
    public boolean isDefault(String name) {
        return false;
    }

    /**
     * This implementation always return false.
     */
    @Override
    public boolean needsSaving() {
        return false;
    }

    @Override
    public void putValue(String name, String value) {
        setValue(name, value);
    }

    @Override
    public void removePropertyChangeListener(IPropertyChangeListener listener) {
        removeListenerObject(listener);
        if (!isListenerAttached()) {
            stopListening();
        }
    }

    /**
     * Sets the value in the property cache and in application setting. This function should generate an event and fire a
     * property change.
     * 
     * @param p
     * @param name
     * @param value
     */
    protected void set(String name, String value) {
        Assert.isTrue(name != null);
        // Update the manager
        try {
            this.setting.setByName(name, value);
        } catch (ManagerException e) {
            PlanimodPolicy.showException(e);
        }
    }

    /**
     * This implementation does nothing.
     */
    @Override
    public void setDefault(String name, boolean value) {
        // Does nothing
    }

    /**
     * This implementation does nothing.
     */
    @Override
    public void setDefault(String name, double value) {
        // Does nothing.
    }

    /**
     * This implementation does nothing.
     */
    @Override
    public void setDefault(String name, float value) {
        // Does nothing
    }

    /**
     * This implementation does nothing.
     */
    @Override
    public void setDefault(String name, int value) {
        // Does nothing
    }

    /**
     * This implementation does nothing.
     */
    @Override
    public void setDefault(String name, long value) {
        // Does nothing
    }

    /**
     * This implementation does nothing.
     */
    @Override
    public void setDefault(String name, String defaultObject) {
        // Does nothing
    }

    /**
     * This implementation sets the setting to null. The application manager should handle the default value.
     */
    @Override
    public void setToDefault(String name) {
        set(name, null);
    }

    /*
     * (non-Javadoc) Method declared on IPreferenceStore.
     */
    @Override
    public void setValue(String name, boolean value) {
        boolean oldValue = getBoolean(name);
        if (oldValue != value) {
            set(name, value == true ? IPreferenceStore.TRUE : IPreferenceStore.FALSE);
        }
    }

    /*
     * (non-Javadoc) Method declared on IPreferenceStore.
     */
    @Override
    public void setValue(String name, double value) {
        double oldValue = getDouble(name);
        if (oldValue != value) {
            set(name, Double.toString(value));
        }
    }

    /*
     * (non-Javadoc) Method declared on IPreferenceStore.
     */
    @Override
    public void setValue(String name, float value) {
        float oldValue = getFloat(name);
        if (oldValue != value) {
            set(name, Float.toString(value));
        }
    }

    /*
     * (non-Javadoc) Method declared on IPreferenceStore.
     */
    @Override
    public void setValue(String name, int value) {
        int oldValue = getInt(name);
        if (oldValue != value) {
            set(name, Integer.toString(value));
        }
    }

    /*
     * (non-Javadoc) Method declared on IPreferenceStore.
     */
    @Override
    public void setValue(String name, long value) {
        long oldValue = getLong(name);
        if (oldValue != value) {
            set(name, Long.toString(value));
        }
    }

    /*
     * (non-Javadoc) Method declared on IPreferenceStore.
     */
    @Override
    public void setValue(String name, String value) {
        String oldValue = getString(name);
        if (oldValue == null || !oldValue.equals(value)) {
            set(name, value);
        }
    }

    /**
     * Called when the first listener is added.
     */
    protected void startListening() {
        this.setting.addObserver(ManagerEvent.ALL, this.observer);
    }

    /**
     * Remove listener from the manager.
     */
    protected void stopListening() {
        this.setting.removeObserver(ManagerEvent.ALL, this.observer);
    }
}
