/*
 * Copyright (c) 2006-2014 DMDirc Developers
 *
 * 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 com.dmdirc;

import com.dmdirc.ClientModule.GlobalConfig;
import com.dmdirc.commandparser.CommandType;
import com.dmdirc.commandparser.parsers.GlobalCommandParser;
import com.dmdirc.interfaces.Connection;
import com.dmdirc.interfaces.FrameCloseListener;
import com.dmdirc.interfaces.config.AggregateConfigProvider;
import com.dmdirc.interfaces.config.ConfigChangeListener;
import com.dmdirc.messages.MessageSinkManager;
import com.dmdirc.ui.WindowManager;
import com.dmdirc.ui.core.components.WindowComponent;
import com.dmdirc.ui.input.TabCompleterFactory;
import com.dmdirc.util.URLBuilder;

import java.util.Arrays;

import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;

/**
 * A window which can be used to execute global commands.
 */
@Singleton
public class GlobalWindow extends FrameContainer {

    /**
     * Creates a new instance of GlobalWindow.
     *
     * @param config              The ConfigManager to retrieve settings from.
     * @param parser              The command parser to use to parse input.
     * @param tabCompleterFactory The factory to use to create tab completers.
     * @param messageSinkManager  The sink manager to use to dispatch messages.
     * @param urlBuilder          The URL builder to use when finding icons.
     * @param eventBus            The bus to dispatch events on.
     */
    @Inject
    public GlobalWindow(
            @GlobalConfig final AggregateConfigProvider config,
            final GlobalCommandParser parser,
            final TabCompleterFactory tabCompleterFactory,
            final MessageSinkManager messageSinkManager,
            final URLBuilder urlBuilder,
            final DMDircMBassador eventBus) {
        super(null, "icon", "Global", "(Global)", config, urlBuilder, parser,
                tabCompleterFactory.getTabCompleter(config, CommandType.TYPE_GLOBAL),
                messageSinkManager, eventBus,
                Arrays.asList(
                        WindowComponent.TEXTAREA.getIdentifier(),
                        WindowComponent.INPUTFIELD.getIdentifier()));
    }

    @Override
    public Connection getConnection() {
        return null;
    }

    @Override
    public void sendLine(final String line) {
        addLine("commandError", "You may only enter commands in the global window.");
    }

    @Override
    public int getMaxLineLength() {
        return -1;
    }

    /** Handles the state of the global window. */
    @Singleton
    public static class GlobalWindowManager implements ConfigChangeListener {

        /** Provider to use to obtain global window instances. */
        private final Provider<GlobalWindow> globalWindowProvider;
        /** The global configuration to read settings from. */
        private final AggregateConfigProvider globalConfig;
        /** The provider to use to retrieve a window manager. */
        private final Provider<WindowManager> windowManagerProvider;

        /**
         * Creates a new instance of {@link GlobalWindowManager}.
         *
         * @param globalWindowProvider  The provider to use to obtain global windows.
         * @param globalConfig          Configuration provider to read settings from.
         * @param windowManagerProvider The provider to use to retrieve a window manager.
         */
        @Inject
        public GlobalWindowManager(
                final Provider<GlobalWindow> globalWindowProvider,
                @GlobalConfig final AggregateConfigProvider globalConfig,
                final Provider<WindowManager> windowManagerProvider) {
            this.globalWindowProvider = globalWindowProvider;
            this.globalConfig = globalConfig;
            this.windowManagerProvider = windowManagerProvider;
        }

        @Override
        public void configChanged(final String domain, final String key) {
            updateWindowState();
        }

        /**
         * Initialises the global window if it's enabled in the config.
         */
        public void init() {
            globalConfig.addChangeListener("general", "showglobalwindow", this);
            updateWindowState();
        }

        /**
         * Updates the state of the global window in line with the general.showglobalwindow config
         * setting.
         */
        protected void updateWindowState() {
            final WindowManager windowManager = windowManagerProvider.get();
            final GlobalWindow globalWindow = globalWindowProvider.get();
            final boolean globalWindowExists = windowManager.getRootWindows()
                    .contains(globalWindow);

            if (globalConfig.getOptionBool("general", "showglobalwindow")) {
                if (!globalWindowExists) {
                    addCloseListener(globalWindow);
                    windowManager.addWindow(globalWindow);
                }
            } else {
                if (globalWindowExists) {
                    globalWindow.close();
                }
            }
        }

        /**
         * Adds a {@link FrameCloseListener} to the specified window to update the global window
         * state if the user closes it from the UI.
         *
         * @param window The window to add a listener to.
         */
        private void addCloseListener(final GlobalWindow window) {
            window.addCloseListener(new FrameCloseListener() {
                @Override
                public void windowClosing(final FrameContainer container) {
                    container.removeCloseListener(this);
                }
            });
        }

    }

}

@@ -1338,57 +1338,8 @@
 on;%0A
-import com.dmdirc.interfaces.FrameCloseListener;%0A
 impo
@@ -1391,24 +1391,24 @@
 igProvider;%0A
+
 import com.d
@@ -2481,29 +2481,16 @@
 lWindow(
-%0A            
 @GlobalC
@@ -2578,28 +2578,16 @@
  parser,
-%0A           
  final T
@@ -2682,28 +2682,16 @@
 Manager,
-%0A           
  final U
@@ -3002,33 +3002,8 @@
 ist(
-%0A                        
 Wind
@@ -4378,33 +4378,16 @@
 Manager(
-%0A                
 final Pr
@@ -5529,16 +5529,36 @@
 Exists =
+%0A                   
  windowM
@@ -5580,37 +5580,16 @@
 indows()
-%0A                    
 .contain
@@ -5730,60 +5730,8 @@
 ) %7B%0A
-                    addCloseListener(globalWindow);%0A
     
@@ -5954,590 +5954,12 @@
   %7D%0A
-%0A        /**%0A         * Adds a %7B@link FrameCloseListener%7D to the specified window to update the global window%0A         * state if the user closes it from the UI.%0A         *%0A         * @param window The window to add a listener to.%0A         */%0A        private void addCloseListener(final GlobalWindow window) %7B%0A            window.addCloseListener(new FrameCloseListener() %7B%0A                @Override%0A                public void windowClosing(final FrameContainer container) %7B%0A                    container.removeCloseListener(this);%0A                %7D%0A            %7D);%0A        %7D%0A%0A    %7D%0A
+    %7D
 %0A%7D%0A

Remove GlobalWindowManager close listener.