/*
 * The MIT License
 *
 * Copyright (c) 2014 Mads Mohr Christensen
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.jenkinsci.plugins.TwoFactorAuth;

import hudson.Extension;
import hudson.Plugin;
import hudson.util.DescribableList;
import hudson.util.PluginServletFilter;
import jenkins.model.GlobalConfiguration;
import jenkins.model.GlobalConfigurationCategory;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.StaplerRequest;

import javax.servlet.ServletException;
import java.io.IOException;

/**
 * @author Mads Mohr Christensen
 */
public class PluginImpl extends Plugin {

    private boolean enabled = false;
    private DescribableList<TwoFactorAuthProvider, TwoFactorAuthProviderDescriptor> twoFactorAuthProviders = new DescribableList<TwoFactorAuthProvider, TwoFactorAuthProviderDescriptor>(this);
    private TwoFactorAuthFilter filter = null;

    @Override
    public void postInitialize() throws Exception {
        load();
        startFilter();
    }

    @Override
    public void stop() throws Exception {
        stopFilter();
    }

    @Extension
    public static final class GlobalConfigurationImpl extends GlobalConfiguration {

        @Override
        public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
            try {
                PluginImpl instance = PluginImpl.getInstance();
                instance.setEnabled(json.has("enabled"));
                JSONObject enabled = json.getJSONObject("enabled");
                if (!enabled.isNullObject()) {
                    JSONObject twoFactorAuthProviders = enabled.getJSONObject("twoFactorAuthProviders");
                    if (!twoFactorAuthProviders.isNullObject()) {
                        instance.getTwoFactorAuthProviders().rebuild(req, twoFactorAuthProviders, TwoFactorAuthProvider.all());
                    }
                } else {
                    instance.getTwoFactorAuthProviders().clear();
                }
                instance.save();
                instance.stopFilter();
                instance.startFilter();
                return true;
            } catch (IOException e) {
                throw new FormException(e, "enabled");
            } catch (ServletException e) {
                throw new FormException(e, "twoFactorAuthProviders");
            }
        }

        @Override
        public GlobalConfigurationCategory getCategory() {
            return GlobalConfigurationCategory.get(GlobalConfigurationCategory.Security.class);
        }
    }

    public static PluginImpl getInstance() {
        return Jenkins.getInstance().getPlugin(PluginImpl.class);
    }

    protected void startFilter() throws ServletException {
        if (enabled && !twoFactorAuthProviders.isEmpty()) {
            filter = new TwoFactorAuthFilter(this);
            PluginServletFilter.addFilter(filter);
        }
    }

    protected void stopFilter() throws ServletException {
        if (filter != null) {
            PluginServletFilter.removeFilter(filter);
            filter = null;
        }
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public DescribableList<TwoFactorAuthProvider, TwoFactorAuthProviderDescriptor> getTwoFactorAuthProviders() {
        return twoFactorAuthProviders;
    }

    public void setTwoFactorAuthProviders(DescribableList<TwoFactorAuthProvider, TwoFactorAuthProviderDescriptor> twoFactorAuthProviders) {
        this.twoFactorAuthProviders = twoFactorAuthProviders;
    }

}
