package Common.Database.Objects.Splitter;
import Common.Database.Tables.DBTable;
import Common.Utils.Utils_;

import javax.swing.*;
import java.lang.reflect.Field;
import java.util.Vector;
public class SplittersDBTable extends DBTable<String, Splitter> {
    public SplittersDBTable() {
        super(String.class, Splitter.class);
    }
    private Vector<JSplitPane> InitSplitters(Object form) throws Exception {
        Vector<JSplitPane> res = new Vector<>();
        Class c = form.getClass();
        for (Field field : c.getFields()) {
            if (field.getType().getSimpleName().equals("JSplitPane")) {
                JSplitPane splitPane = (JSplitPane) field.get(form);
                splitPane.setName(field.getName());
                res.add(splitPane);
            }
        }
        return res;
    }
    public void Load(Object form) {
        try {
            Vector<JSplitPane> splitters = InitSplitters(form);
            for (JSplitPane splitPane : splitters) {
                if (Data.containsKey(splitPane.getName())) {
                    splitPane.setDividerLocation(Data.get(splitPane.getName()).position);
                } else {
                    getDb().Insert(new Splitter(splitPane));
                }
            }
        } catch (Exception ex) {
            Utils_.MainLog.PrintException(ex);
        }
    }
    public void Save(Object form) {
        try {
            Vector<JSplitPane> splitters = InitSplitters(form);
            for (JSplitPane splitPane : splitters) {
                Splitter splitter = Data.get(splitPane.getName());
                splitter.position = splitPane.getDividerLocation();
                getDb().Update(splitter);
            }
        } catch (Exception ex) {
            Utils_.MainLog.PrintException(ex);
        }
    }
}
