package Common.UI.Windows;
import Common.Global;
import Common.UI.Themes.ThemeElement;
import GlobalData.FormsParams.DBForm;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.SQLException;
public abstract class Form extends JFrame implements ThemeElement {
    private DBForm info = null;
    public Form() {
        if (getIconName().length() > 0) setIconImage(new ImageIcon(Form.class.getResource(getIconName())).getImage());
        SetListener();
        this.setTitle(Global.isWindows ? getWTitleText() : getUTitleText());
        pack();
        setMinimumSize(new Dimension(getDefaultWidth(), getDefaultHeight()));
    }
    abstract protected JPanel getMainPanel();
    public String getIconName() {
        return "";
    }
    public String getWTitleText() {
        return "";
    }
    public String getUTitleText() {
        return "";
    }
    protected FormType getFormType() {
        return FormType.Undefined;
    }
    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) {
            Global.Log.PrintException(e);
        }
        setContentPane(getMainPanel());
        setVisible(true);
    }
    public void Close() {
        try {
            SaveWindowParameters();
        } catch (Exception e) {
            Global.Log.PrintException(e);
        }
        setVisible(false);
        dispose();
        AfterClose();
    }
    public void AfterClose() {
    }
    public void LoadWindowParameters() throws SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        if (!getFormType().equals(FormType.Undefined))
            if (Global.db.forms.Data.containsKey(getFormType())) {
                info = Global.db.forms.Data.get(getFormType());
                info.Apply(this);
                return;
            }
        setSize(getDefaultWidth(), getDefaultHeight());
        setLocationRelativeTo(getRelative());
    }
    public void SaveWindowParameters() throws Exception {
        if (!getFormType().equals(FormType.Undefined)) {
            if (info != null) {
                info.Init(this);
                Global.db.Update(info);
            } else
                Global.db.Insert(new DBForm(getFormType(), this));
        }
    }
    @Override
    public void applyTheme() {
        //todo -> применение темы.
    }
}
