package yukihane.inqubus;

import java.nio.file.Path;
import java.nio.file.Paths;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import org.apache.commons.configuration.ConfigurationException;
import yukihane.inqubus.config.Config;
import yukihane.inqubus.gui.MainFrame;
import yukihane.inqubus.saccubus.prompt.Prompt;

/**
 * いんきゅばす起動クラス.
 * @author yuki
 */
public class Main {

    private static final Logger logger = LoggerFactory.getLogger(Main.class);

    public static void main(String args[]) {
        final Path path = Paths.get("inqubus.xml");
        boolean showWelcome;
        try {
            Config.INSTANCE.load(path.toString());
            showWelcome = false;
        } catch (ConfigurationException ex) {
            showWelcome = true;
            logger.debug("コンフィグファイルが無いためデフォルト値で起動", ex);
        }

        // 第1引数がメールアドレスと思しき時はさきゅばすフォーマットのコマンドラインであるとみなしてパース
        if (args.length > 0 && args[0].contains("@")) {
            try {
                new Prompt().main(args);
            } catch (Exception ex) {
                logger.error("処理が正常終了しませんでした", ex);
            }
            return;
        }

        final RunWindow invoke = new RunWindow(showWelcome);
        java.awt.EventQueue.invokeLater(invoke);
    }

    private static class RunWindow implements Runnable {

        private final boolean showWelcome;

        private RunWindow(boolean showWelcome) {
            this.showWelcome = showWelcome;
        }

        @Override
        public void run() {
            setLookAndFeel();
            final MainFrame frame = new MainFrame();
            frame.startWatcher();
            frame.setVisible(true);
            if (showWelcome) {
                JOptionPane.showMessageDialog(frame,
                        "<html>設定はメニューの <b>ツール > オプション</b> から行えます</html>",
                        "いんきゅばすへようこそ", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }

    private static void setLookAndFeel() {
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                // System Look & Feel も無いことは無いだろう
            }
        }
    }
}
