package com.rthoni.intellij.codefromds.ui.actions;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.vfs.VirtualFile;
import com.rthoni.intellij.codefromds.business.Generator;
import com.rthoni.intellij.codefromds.dbo.options.GenerateOptions;
import com.rthoni.intellij.codefromds.ui.dialogs.GenerateDialog;
import com.rthoni.intellij.codefromds.ui.others.NotificationsService;

/**
 * Created by robin on 11/14/16.
 */
public class GenerateAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        NotificationsService notificationsService = NotificationsService.getInstance();

        Project project = e.getProject();
        if (project == null) {
            notificationsService.showErrorNotification("Error", "Code FROM ds needs a current project to run");
            return;
        }

        GenerateDialog dlg = new GenerateDialog(project);
        if (!e.getPlace().equals("MainMenu")) {
            final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(e.getDataContext());
            if (file != null) {
                try {
                    GenerateOptions options = Generator.loadOptions(file.getPath());
                    dlg.setOptions(options);
                } catch (Exception e1) {
                    notificationsService.showErrorNotification("Error while loading configuration file", e1.toString());
                    e1.printStackTrace();
                }
            }
        }
        dlg.show();
        int res = dlg.getExitCode();
        if (res == DialogWrapper.OK_EXIT_CODE) {
            GenerateOptions options = dlg.getOptions();
            try {
                Generator.saveOptions(options);
            } catch (Exception e1) {
                notificationsService.showErrorNotification("Error while saving configuration", e1.toString());
                e1.printStackTrace();
            }
            try {
                Generator.generate(options, project);
                notificationsService.showInfoNotification("Generation successful", "Files have been successfully generated");
            } catch (Exception e1) {
                notificationsService.showErrorNotification("Error while generating files", e1.toString());
                e1.printStackTrace();
            }
        }
    }

    @Override
    public void update(AnActionEvent e) {
        if (e.getPlace().equals("MainMenu")) {
            super.update(e);
        }
        else {
            final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(e.getDataContext());
            e.getPresentation().setVisible(file != null && file.getName().equals("code-from-ds.json"));
        }
    }
}
