package com.github.dreamhead.moco.runner.monitor;

import com.github.dreamhead.moco.runner.*;
import com.google.common.collect.Iterables;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

public class MonitorFactory {
    private static Logger logger = LoggerFactory.getLogger(MonitorFactory.class);

    public Runner createShutdownMonitor(final Runner runner, final int shutdownPort, final String shutdownKey) {
        return new MonitorRunner(runner, new ShutdownMonitor(shutdownPort, shutdownKey, new ShutdownListener() {
            @Override
            public void onShutdown() {
                runner.stop();
            }
        }));
    }

    public FileMonitor createConfigurationMonitor(final File configuration, final FileRunner fileRunner) {
        return new FileMonitor(configuration, createListener(fileRunner));
    }

    public Monitor createSettingMonitor(final File settingsFile, final Iterable<File> configurationFiles, final FileRunner fileRunner) {
        List<File> files = newArrayList(settingsFile);
        Iterables.addAll(files, configurationFiles);
        return new FilesMonitor(files, createListener(fileRunner));
    }

    private FileAlterationListenerAdaptor createListener(final FileRunner fileRunner) {
        return new FileAlterationListenerAdaptor() {
            @Override
            public void onFileChange(File file) {
                logger.info("{} change detected.", file.getName());
                try {
                    fileRunner.restart();
                } catch (Exception e) {
                    logger.error("Fail to load configuration in {}.", file.getName());
                    logger.error(e.getMessage());
                }
            }
        };
    }
}

@@ -88,9 +88,121 @@
 ner.
-*
+FileRunner;%0Aimport com.github.dreamhead.moco.runner.MonitorRunner;%0Aimport com.github.dreamhead.moco.runner.Runner
 ;%0Aim
@@ -233,24 +233,28 @@
 ollect.I
-terables
+mmutableList
 ;%0Aimport
@@ -373,16 +373,16 @@
 ctory;%0A%0A
+
 import j
@@ -397,92 +397,8 @@
 ile;
-%0Aimport java.util.List;%0A%0Aimport static com.google.common.collect.Lists.newArrayList;
 %0A%0Apu
@@ -1194,16 +1194,25 @@
         
+Immutable
 List%3CFil
@@ -1226,61 +1226,63 @@
 s = 
-newArrayList(settingsFile);%0A        Iterables
+ImmutableList.%3CFile%3Ebuilder().add(settingsFile)
 .addAll(
 file
@@ -1277,23 +1277,16 @@
 .addAll(
-files, 
 configur
@@ -1296,16 +1296,24 @@
 onFiles)
+.build()
 ;%0A      

replace list with immutable list in create setting monitor