/*
 * Copyright (c) 2006-2015 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.logger;

import com.dmdirc.ClientModule.GlobalConfig;
import com.dmdirc.DMDircMBassador;
import com.dmdirc.config.ConfigBinder;
import com.dmdirc.config.ConfigBinding;
import com.dmdirc.events.AppErrorEvent;
import com.dmdirc.events.ErrorEvent;
import com.dmdirc.events.UserErrorEvent;
import com.dmdirc.interfaces.config.AggregateConfigProvider;

import com.google.common.base.Throwables;
import com.google.common.collect.Lists;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import net.engio.mbassy.listener.Handler;

/**
 * Listens for {@link ErrorEvent}s and writes them to disk.
 */
public class DiskLoggingErrorManager {

    /** The event bus to listen for errors on. */
    private final DMDircMBassador eventBus;
    /** The directory to log errors to. */
    private final Path errorsDirectory;
    /** The config binder to use for settings. */
    private final ConfigBinder configBinder;
    /** Error creating directory, don't write to disk. */
    private boolean directoryError;
    /** Are we logging errors to disk? */
    private boolean logging;

    public DiskLoggingErrorManager(final Path errorsDirectory,
            final DMDircMBassador eventBus,
            @GlobalConfig final AggregateConfigProvider config) {
        this.errorsDirectory = errorsDirectory;
        this.eventBus = eventBus;
        configBinder = config.getBinder();
    }

    public void initialise() {
        configBinder.bind(this, DiskLoggingErrorManager.class);
        eventBus.subscribe(this);
        if (!Files.exists(errorsDirectory)) {
            try {
                Files.createDirectories(errorsDirectory);
            } catch (IOException ex) {
                directoryError = true;
            }
        }
    }

    public boolean isDirectoryError() {
        return directoryError;
    }

    @Handler
    public void handleAppErrorEvent(final AppErrorEvent appError) {
        saveError(appError);
    }

    @Handler
    public void handleUserErrorEvent(final UserErrorEvent userError) {
        saveError(userError);
    }

    @ConfigBinding(domain = "general", key = "logerrors")
    public void handleLoggingSetting(final boolean value) {
        logging = value;
    }

    private void saveError(final ErrorEvent error) {
        if (directoryError || !logging) {
            return;
        }
        final String logName = error.getTimestamp() + "-" + error.getLevel();
        final Path errorFile = errorsDirectory.resolve(logName + ".log");
        final List<String> data = Lists
                .newArrayList("Date: " + new Date(error.getTimestamp()),
                        "Level: " + error.getLevel(),
                        "Description: " + error.getMessage(),
                        "Details: ");
        Arrays.stream(Throwables.getStackTraceAsString(error.getThrowable()).split("\n"))
                .forEach(data::add);
        try {
            Files.write(errorFile, data, Charset.forName("UTF-8"));
        } catch (IOException ex) {
            //Not really anything we can do at this point, so don't try.
        }
    }
}

@@ -2348,16 +2348,378 @@
 gging;%0A%0A
+    /**%0A     * Creates a new instance of this error manager.%0A     *%0A     * @param errorsDirectory The directory to write errors to.  The error manager will try to%0A     *                        create this if it is not present%0A     * @param eventBus        The event bus to listen to errors on%0A     * @param config          The config to read values from%0A     */%0A
     publ
@@ -2772,28 +2772,16 @@
 rectory,
-%0A           
  final D
@@ -2995,32 +2995,129 @@
 inder();%0A    %7D%0A%0A
+    /**%0A     * Initialises the error manager.  Must be called before logging will start.%0A     */%0A
     public void 
@@ -3456,24 +3456,295 @@
    %7D%0A    %7D%0A%0A
+    /**%0A     * This is true is there was an error creating the error directory.  If this is true the logger%0A     * will not attempt to write to disk irrespective of the config setting.%0A     *%0A     * @return true if there was an error creating the error directory%0A     */%0A
     public b
@@ -3818,39 +3818,32 @@
    @Handler%0A    
-public 
 void handleAppEr
@@ -3932,31 +3932,24 @@
 Handler%0A    
-public 
 void handleU
@@ -4091,31 +4091,24 @@
 rrors%22)%0A    
-public 
 void handleL

Add some javadoc.