package be.iminds.ilabt.jfed.experimenter_gui.timeline.controller.action;

import be.iminds.ilabt.jfed.experimenter_gui.timeline.model.TimelineModel;
import be.iminds.ilabt.jfed.experimenter_gui.timeline.view.TimelineComponent;
import be.iminds.ilabt.jfed.experimenter_gui.timeline.view.UpdateEvent;
import be.iminds.ilabt.jfed.rspec.model.controller.ExperimentCommand;

import java.util.Objects;

/**
 * @author Cedric
 */
public class UpdateCommandAction implements IAction {

    private final ExperimentCommand o1, o2, backup;

    /**
     * @param o1 old
     * @param o2 new
     */
    public UpdateCommandAction(ExperimentCommand o1, ExperimentCommand o2) {
        this.o1 = o1;
        this.o2 = o2;
        backup =
                new ExperimentCommand(o1.getTag(), o1.getNodeUniqueID(), o1.getBarrierSegmentOrderNumber(), o1.getCommand(), o1.getStartingTime(), o1.getDuration());
    }

    @Override
    public boolean execute(TimelineModel model, TimelineComponent view) {

        if (!Objects.equals(o1.getCommand(), o2.getCommand())) {
            o1.setCommand(o2.getCommand());
        }

        if (o1.getStartingTime().toMillis() != o2.getStartingTime().toMillis()) {
            o1.setStartingTime(o2.getStartingTime());
        }

        if (!Objects.equals(o1.getDuration(), o2.getDuration())) {
            o1.setDuration(o2.getDuration());
        }

        if (!Objects.equals(o1.getNodeUniqueID(), o2.getNodeUniqueID())) {
            o1.setNodeUniqueID(o2.getNodeUniqueID());
        }

        if (!Objects.equals(o1.getTag(), o2.getTag())) {
            o1.setTag(o2.getTag());
        }


        view.update(UpdateEvent.UPDATE_COMMAND, o1);

        return true;
    }

    @Override
    public boolean undo(TimelineModel model, TimelineComponent view) {

        if (o1.getCommand() != null) {
            o1.setCommand(backup.getCommand());
        }

        if (!Objects.equals(o1.getStartingTime(), backup.getStartingTime())) {
            o1.setStartingTime(backup.getStartingTime());
        }

        if (!Objects.equals(o1.getDuration(), backup.getDuration())) {
            o1.setDuration(backup.getDuration());
        }

        if (!Objects.equals(o1.getNodeUniqueID(), backup.getNodeUniqueID())) {
            o1.setNodeUniqueID(backup.getNodeUniqueID());
        }

        if (!Objects.equals(o1.getTag(), backup.getTag())) {
            o1.setTag(backup.getTag());
        }

        view.update(UpdateEvent.UPDATE_COMMAND, o1);

        return true;
    }

}
