package Common.Visual.Windows;
import Common.Utils.Utils_;
import Common.Visual.Themes.ThemeElement;
import Common.Database.Objects.DBForm.DBForm;
import _VisualDVM.Global;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public abstract class Form extends JFrame implements ThemeElement {
    private DBForm dbInfo = null;
    public Form() {
        if (getIconPath()!=null) setIconImage(Utils_.getIcon(getIconPath()).getImage());
        SetListener();
        this.setTitle(Utils_.isWindows() ? getWTitleText() : getUTitleText());
        pack();
        setMinimumSize(new Dimension(getDefaultWidth(), getDefaultHeight()));
    }
    abstract protected JPanel getMainPanel();
    public String getIconPath() {
        return null;
    }
    public String getWTitleText() {
        return "";
    }
    public String getUTitleText() {
        return "";
    }
    protected String getFormKey() {
        return null;
    }
    protected void SetListener() {
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                Close();
            }
        });
    }
    public int getDefaultWidth() {
        return 800;
    }
    public int getDefaultHeight() {
        return 450;
    }
    /*
     *вызывать после перегрузки, чтобы отобразить окно.
     */
    public Component getRelative() {
        return null;
    }
    public void Show() {
        try {
            LoadWindowParameters();
        } catch (Exception e) {
            Utils_.MainLog.PrintException(e);
        }
        setContentPane(getMainPanel());
        setVisible(true);
    }
    public void Close() {
        try {
            SaveWindowParameters();
        } catch (Exception e) {
            Utils_.MainLog.PrintException(e);
        }
        setVisible(false);
        dispose();
        AfterClose();
    }
    public void AfterClose() {
    }
    public void LoadWindowParameters() throws Exception {
        if (getFormKey()!=null)
            if (Global.mainModule.getDb().forms.Data.containsKey(getFormKey())) {
                dbInfo = Global.mainModule.getDb().forms.Data.get(getFormKey());
                dbInfo.Apply(this);
                return;
            }
        setSize(getDefaultWidth(), getDefaultHeight());
        setLocationRelativeTo(getRelative());
    }
    public void SaveWindowParameters() throws Exception {
        if (getFormKey()!=null) {
            if (dbInfo != null) {
                dbInfo.Init(this);
                Global.mainModule.getDb().Update(dbInfo);
            } else
                Global.mainModule.getDb().Insert(new DBForm(getFormKey(), this));
        }
    }
    @Override
    public void applyTheme() {
        //todo -> применение темы.
    }
}
