package _VisualDVM.Passes.All;
import Common.Passes.Pass;
import Common.Visual.Windows.Dialog.PercentsForm;
import Common.Visual.Windows.Dialog.Text.TextFieldDialog;
import _VisualDVM.Global;
import _VisualDVM.Passes.PassCode;
import _VisualDVM.ProjectData.SapforData.SapforProperties;

import java.lang.reflect.Field;
public class UpdateSapforProperty extends Pass<Object> {
    SapforProperties properties = null;
    String name = "";
    Field field = null;
    Object oldValue = null;
    Object newValue = null;
    @Override
    protected boolean canStart(Object... args) throws Exception {
        properties = Global.mainModule.getProject().sapforProperties;
        //---
        name = (String) args[0];
        String description = properties.getFieldDescription(name);
        field = SapforProperties.class.getField(name);
        oldValue = field.get(properties);
        newValue = null;
        //-
        if (args.length == 1) {
            if (oldValue instanceof Boolean) {
                newValue = !(Boolean) oldValue;
                return true;
            } else {
                switch (name) {
                    case "GCOVLimit":
                    case "MAX_SHADOW_WIDTH":
                        PercentsForm percentsForm = new PercentsForm();
                        if (percentsForm.ShowDialog(description, oldValue))
                            newValue = percentsForm.Result;
                        break;
                    case "DVMConvertationOptions":
                    case "ANALYSIS_OPTIONS":
                        TextFieldDialog textFieldDialog = new TextFieldDialog();
                        if (textFieldDialog.ShowDialog(description, oldValue)) {
                            newValue = textFieldDialog.Result;
                            if (newValue.toString().isEmpty())
                                newValue = " ";
                        }
                        break;
                    default:
                        break;
                }
            }
        } else
            newValue = args[1];
        //--
        return newValue != null && !newValue.equals(oldValue);
    }
    @Override
    protected void body() throws Exception {
        field.set(properties, newValue);
        properties.Update();
    }
    @Override
    protected void showDone() throws Exception {
        switch (name) {
            case "GCOVLimit":
                if (Global.mainModule.HasFile())
                    Global.mainModule.getFile().form.ShowGCOV();
                break;
            case "MPI_PROGRAM":
                Global.mainModule.getPass(PassCode.CleanAnalyses).Do();
                ((SPF_GetArrayDistributionOnlyAnalysis)
                        Global.mainModule.getPass(PassCode.SPF_GetArrayDistributionOnlyAnalysis)).RefreshControls();
                break;
            case "Precompilation":
                Global.mainModule.getSapfor().ResetAllAnalyses();
                break;
        }
    }
}