/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.netbeans.modules.javascript.bower.ui.options;

import java.awt.EventQueue;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.JComponent;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.netbeans.modules.javascript.bower.options.BowerOptions;
import org.netbeans.modules.javascript.bower.options.BowerOptionsValidator;
import org.netbeans.modules.web.common.api.ValidationResult;
import org.netbeans.spi.options.OptionsPanelController;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;

@NbBundle.Messages("BowerOptionsPanelController.name=Bower")
@OptionsPanelController.SubRegistration(
    location = BowerOptionsPanelController.OPTIONS_CATEGORY,
    id = BowerOptionsPanelController.OPTIONS_SUBCATEGORY,
    displayName = "#BowerOptionsPanelController.name" // NOI18N
)
public class BowerOptionsPanelController extends OptionsPanelController implements ChangeListener {

    public static final String OPTIONS_CATEGORY = "Html5"; // NOI18N
    public static final String OPTIONS_SUBCATEGORY = "Bower"; // NOI18N
    public static final String OPTIONS_PATH = OPTIONS_CATEGORY + "/" + OPTIONS_SUBCATEGORY; // NOI18N

    private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);

    // @GuardedBy("EDT")
    private BowerOptionsPanel bowerOptionsPanel;
    private volatile boolean changed = false;
    private boolean firstOpening = true;


    @Override
    public void update() {
        assert EventQueue.isDispatchThread();
        if (firstOpening || !isChanged()) { // if panel is not modified by the user and he switches back to this panel, set to default
            firstOpening = false;
            getPanel().setBower(getBowerOptions().getBower());
            getPanel().setIgnoreBowerComponents(getBowerOptions().isIgnoreBowerComponents());
        }
        changed = false;
    }

    @Override
    public void applyChanges() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                getBowerOptions().setBower(getPanel().getBower());
                getBowerOptions().setIgnoreBowerComponents(getPanel().isIgnoreBowerComponents());
                changed = false;
            }
        });
    }

    @Override
    public void cancel() {
        if (isChanged()) { // if panel is modified by the user and options window closes, discard any changes
            getPanel().setBower(getBowerOptions().getBower());
            getPanel().setIgnoreBowerComponents(getBowerOptions().isIgnoreBowerComponents());
        }
    }

    @Override
    public boolean isValid() {
        assert EventQueue.isDispatchThread();
        BowerOptionsPanel panel = getPanel();
        ValidationResult result = new BowerOptionsValidator()
                .validateBower(panel.getBower())
                .getResult();
        // errors
        if (result.hasErrors()) {
            panel.setError(result.getFirstErrorMessage());
            return false;
        }
        // warnings
        if (result.hasWarnings()) {
            panel.setWarning(result.getFirstWarningMessage());
            return true;
        }
        // everything ok
        panel.setError(" "); // NOI18N
        return true;
    }

    @Override
    public boolean isChanged() {
        String saved = getBowerOptions().getBower();
        String current = getPanel().getBower().trim();
        if (saved == null ? !current.isEmpty() : !saved.equals(current)) {
            return true;
        }
        return getBowerOptions().isIgnoreBowerComponents() != getPanel().isIgnoreBowerComponents();
    }

    @Override
    public JComponent getComponent(Lookup masterLookup) {
        assert EventQueue.isDispatchThread();
        return getPanel();
    }

    @Override
    public HelpCtx getHelpCtx() {
        return new HelpCtx("org.netbeans.modules.javascript.bower.ui.options.BowerOptionsPanelController"); // NOI18N
    }

    @Override
    public void addPropertyChangeListener(PropertyChangeListener l) {
        propertyChangeSupport.addPropertyChangeListener(l);
    }

    @Override
    public void removePropertyChangeListener(PropertyChangeListener l) {
        propertyChangeSupport.removePropertyChangeListener(l);
    }

    @Override
    public void stateChanged(ChangeEvent e) {
        if (!changed) {
            changed = true;
            propertyChangeSupport.firePropertyChange(OptionsPanelController.PROP_CHANGED, false, true);
        }
        propertyChangeSupport.firePropertyChange(OptionsPanelController.PROP_VALID, null, null);
    }

    private BowerOptionsPanel getPanel() {
        assert EventQueue.isDispatchThread();
        if (bowerOptionsPanel == null) {
            bowerOptionsPanel = new BowerOptionsPanel();
            bowerOptionsPanel.addChangeListener(this);
        }
        return bowerOptionsPanel;
    }

    private BowerOptions getBowerOptions() {
        return BowerOptions.getInstance();
    }

}
