/**
 * Copyright (C) 2019 Patrik Dufresne Service Logiciel <info@patrikdufresne.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package com.planimod.core.planif;

import com.patrikdufresne.ilp.Constraint;
import com.patrikdufresne.ilp.util.ConstraintSnapshot;
import com.patrikdufresne.ilp.util.Constraints;

/**
 * Abstract implementation to support a single constraint.
 */
public abstract class AbstractConstraintRunnable extends SolveRunnable {

    protected Constraint constraint;

    protected ConstraintSnapshot constraintSnapshot;

    /**
     * @param problem
     *            reference to ProblemBuilder
     */
    public AbstractConstraintRunnable(ProblemBuilder problem) {
        super(problem);
    }

    /**
     * This implementation restore the constraint snapshot.
     */
    @Override
    public void engage() {
        if (this.constraintSnapshot == null) {
            throw new RuntimeException("snaptshot not available.");
        }
        this.constraint = this.constraintSnapshot.restore(pb.lp);
        this.constraintSnapshot = null;
    }

    /**
     * This implementation release the constraints and keep a reference of it as a snapshot.
     */
    @Override
    public void release() {
        if (this.constraint == null) {
            throw new RuntimeException("constraint not available.");
        }
        this.constraintSnapshot = Constraints.release(this.constraint);
        this.constraint = null;
    }

    /**
     * This implementation check if the constraint already exists.
     */
    @Override
    public boolean run() throws GeneratePlanifException {
        // Check if the constraint already exists.
        if (this.constraint != null) {
            throw new RuntimeException("constraint already exists");
        }
        return super.run();
    }

    /**
     * This function release and dispose the constraint.
     */
    @Override
    protected void unfeasible() throws GeneratePlanifException {
        // Dispose the constraint
        if (this.constraint != null) {
            this.constraint.dispose();
            this.constraint = null;
        }
    }
}