package org.ui;

import com.formdev.flatlaf.FlatDarkLaf;
import org.renderer.PostProcessConfig;
import org.ui.editors.code.CodeEditor;
import org.ui.editors.map.MapEditor;
import org.ui.icons.IconLoader;
import org.world.World;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;


public class UIAccess
        implements AutoCloseable {
    private JFrame startUpWindow;
    private JProgressBar infoLog;
    private Documentation docs;
    private MapEditor mapEditor;
    private CodeEditor codeEditor;
    private BufferedImage windowIcon;

    public UIAccess() {
        try {


            this.windowIcon = IconLoader.loadWindowIcon();


            if (!FlatDarkLaf.setup()) {

            }


            this.infoLog = new JProgressBar(0, 0, 100);
            this.infoLog.setStringPainted(true);


            this.startUpWindow = new JFrame("RTX-GYTEBOT");
            this.startUpWindow.setIconImage(this.windowIcon);
            this.startUpWindow.setUndecorated(true);
            this.startUpWindow.setDefaultCloseOperation(0);
            this.startUpWindow.getContentPane().setLayout(new BorderLayout());
            this.startUpWindow.getContentPane().add(new JLabel(new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/data/icons/startup.png")))), "Center");
            this.startUpWindow.getContentPane().add(this.infoLog, "South");
            this.startUpWindow.pack();
            this.startUpWindow.setLocationRelativeTo(null);
            this.startUpWindow.setVisible(true);
        } catch (IOException | NullPointerException e) {

            this.startUpWindow.dispose();
            throw new AssertionError("Unable to load or find startup image");
        }
    }


    public final boolean windowCloseRequest() {
        return !(!this.mapEditor.getWindowCloseRequest() && !this.codeEditor.getWindowCloseRequest());
    }


    public final void apply(World world, PostProcessConfig postProcessConfig) {
        this.mapEditor = new MapEditor(world);
        this.mapEditor.setIconImage(this.windowIcon);


        this.codeEditor = new CodeEditor(world, postProcessConfig);
        this.codeEditor.setIconImage(this.windowIcon);
    }


    public final void openDocs() {
        this.docs = new Documentation();
    }


    public void putInfoLoadingMessage(String message, int progress) {
        this.infoLog.setString(message);
        this.infoLog.setValue(progress);
    }


    public final void close() {
        this.startUpWindow.setVisible(false);
        this.startUpWindow.dispose();
    }


    public BufferedImage getWindowIcon() {
        return this.windowIcon;
    }
}
