/*
 * 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.commandparser.auto;

import com.dmdirc.commandline.CommandLineOptionsModule.Directory;
import com.dmdirc.commandline.CommandLineOptionsModule.DirectoryType;
import com.dmdirc.interfaces.Migrator;
import com.dmdirc.util.io.ConfigFile;
import com.dmdirc.util.io.InvalidConfigFileException;

import com.google.common.base.Joiner;
import com.google.common.base.Optional;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Singleton;

/**
 * Migrates server/network-based action performs into auto commands.
 */
@Singleton
public class ActionServerPerformMigrator implements Migrator {

    private final File directory;
    private final AutoCommandManager autoCommandManager;

    @Inject
    public ActionServerPerformMigrator(@Directory(DirectoryType.ACTIONS) final String directory,
            final AutoCommandManager autoCommandManager) {
        this.directory = new File(directory, "performs");
        this.autoCommandManager = autoCommandManager;
    }

    @Override
    public boolean needsMigration() {
        return directory.exists();
    }

    @Override
    public void migrate() {
        @Nullable final File[] files = directory.listFiles();
        if (files != null) {
            for (File child : files) {
                if (migrate(child)) {
                    child.delete();
                }
            }
        }
        directory.delete();
    }

    /**
     * Migrates the specified file.
     *
     * @param file The file to be migrated.
     *
     * @return True if the file was migrated successfully, false otherwise.
     */
    private boolean migrate(final File file) {
        try {
            final ConfigFile configFile = new ConfigFile(file);
            configFile.read();

            final String response = Joiner.on('\n').join(configFile.getFlatDomain("response"));
            final Optional<String> server = getCondition(configFile, "SERVER_NAME");
            final Optional<String> network = getCondition(configFile, "SERVER_NETWORK");
            final Optional<String> profile = getCondition(configFile,
                    "SERVER_PROFILE.IDENTITY_NAME");

            autoCommandManager.addAutoCommand(new AutoCommand(server, network, profile, response));
            return true;
        } catch (IOException | InvalidConfigFileException | NumberFormatException ex) {
            return false;
        }
    }

    private Optional<String> getCondition(final ConfigFile configFile, final String component) {
        for (Map.Entry<String, Map<String, String>> section : configFile.getKeyDomains().entrySet()) {
            if (section.getKey().startsWith("condition")
                    && component.equals(section.getValue().get("component"))) {
                return Optional.fromNullable(section.getValue().get("target"));
            }
        }
        return Optional.absent();
    }

}

@@ -1161,16 +1161,51 @@
 .auto;%0A%0A
+import com.dmdirc.DMDircMBassador;%0A
 import c
@@ -1332,16 +1332,56 @@
 ryType;%0A
+import com.dmdirc.events.AppErrorEvent;%0A
 import c
@@ -1407,24 +1407,61 @@
 s.Migrator;%0A
+import com.dmdirc.logger.ErrorLevel;%0A
 import com.d
@@ -1624,29 +1624,8 @@
 l;%0A%0A
-import java.io.File;%0A
 impo
@@ -1664,52 +1664,111 @@
 ava.
-util.Map;%0A%0Aimport javax.annotation.Nullable;
+nio.file.DirectoryStream;%0Aimport java.nio.file.Files;%0Aimport java.nio.file.Path;%0Aimport java.util.Map;%0A
 %0Aimp
@@ -1994,20 +1994,20 @@
 e final 
-File
+Path
  directo
@@ -2066,16 +2066,60 @@
 Manager;
+%0A    private final DMDircMBassador eventBus;
 %0A%0A    @I
@@ -2163,16 +2163,29 @@
 igrator(
+%0A            
 @Directo
@@ -2216,22 +2216,20 @@
 ) final 
-String
+Path
  directo
@@ -2287,16 +2287,60 @@
 dManager
+,%0A            final DMDircMBassador eventBus
 ) %7B%0A    
@@ -2364,28 +2364,26 @@
 y = 
-new File(directory, 
+directory.resolve(
 %22per
@@ -2441,24 +2441,58 @@
 andManager;%0A
+        this.eventBus = eventBus;%0A
     %7D%0A%0A    @
@@ -2553,16 +2553,34 @@
  return 
+Files.isDirectory(
 director
@@ -2584,16 +2584,8 @@
 tory
-.exists(
 );%0A 
@@ -2644,126 +2644,136 @@
     
-@Nullable final File%5B%5D files = directory.listFiles();%0A        if (files != null) %7B%0A            for (File child : files
+try (DirectoryStream%3CPath%3E directoryStream = Files.newDirectoryStream(directory)) %7B%0A            for (Path path : directoryStream
 ) %7B%0A
@@ -2800,21 +2800,20 @@
 migrate(
-child
+path
 )) %7B%0A   
@@ -2833,21 +2833,21 @@
     
-child
+Files
 .delete(
 );%0A 
@@ -2838,24 +2838,28 @@
 iles.delete(
+path
 );%0A         
@@ -2893,37 +2893,220 @@
     
-%7D%0A        directory.delete();
+    Files.delete(directory);%0A        %7D catch (IOException ex) %7B%0A            eventBus.publish(new AppErrorEvent(ErrorLevel.MEDIUM, ex,%0A                    %22Unable to migrate performs%22, ex.getMessage()));%0A        %7D
 %0A   
@@ -3329,20 +3329,20 @@
 e(final 
-File
+Path
  file) %7B

Make the ActionServerPerformMigrator use paths.