// $Id: LeftAddition.java,v 1.9 2004/02/27 16:29:56 m31 Exp $
//
// This file is part of the program suite "Principia Mathematica II"
// which is a working prototype for the main project:
// "Hilbert II" - http://www.qedeq.org
//
// Copyright 2001-2004  Michael Meyling <mime@qedeq.org>.
//
// "Principia Mathematica II" is free software; you can redistribute
// it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation; either
// version 2 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 General Public License for more details.

package com.meyling.principia.logic.rule;


import com.meyling.principia.argument.AbstractArgumentList;
import com.meyling.principia.argument.Argument;
import com.meyling.principia.argument.ArgumentException;
import com.meyling.principia.argument.Counter;
import com.meyling.principia.argument.Text;
import com.meyling.principia.logic.basic.AbstractFormula;
import com.meyling.principia.logic.basic.BasicPatternVariables;
import com.meyling.principia.logic.basic.Disjunction;
import com.meyling.principia.logic.basic.Formula;
import com.meyling.principia.logic.basic.Implication;
import com.meyling.principia.logic.basic.PropositionVariable;
import com.meyling.principia.logic.paragraph.Axiom;
import com.meyling.principia.logic.paragraph.ParagraphCreator;
import com.meyling.principia.logic.paragraph.ProofLine;
import com.meyling.principia.logic.paragraph.ProofLineList;
import com.meyling.principia.logic.paragraph.RuleDeclaration;
import com.meyling.principia.logic.paragraph.Sentence;
import com.meyling.principia.module.Module;
import com.meyling.principia.module.Version;


/**
 * Implemention of &quot;addition&quot; on the left side.
 * <p>
 * <code>      A1 => A2      </code><p>
 * <code>--------------------</code><p>
 * <code> A3 v A3 => A3 v A2 </code><p>
 *
 * @version $Revision: 1.9 $
 * @author  Michael Meyling
 */
public class LeftAddition extends AbstractArgumentList
        implements Argument, Rule {

    /** minimum version required for using this rule */
    private final static Version version;

    /** proof line of <code>A1 => A2</code>*/
    private final int n;

    /** add this formula */
    private final Formula additional;


    /**
     * Initialize version information.
     */
    static {
        try {
            version = new Version(
                    new Argument[] {new Text("1.01.04")});
        } catch (ArgumentException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }


    /**
     * Constructs a left addition rule.
     *
     * @param   arguments
     *          <ul>
     *            <li>first argument is a proof line number
     *              to operate on, this proof line must be an implication
     *            </li>
     *            <li>second list entry must be a formula
     *            </li>
     *          </ul>
     * @throws  ArgumentException    if there are not exactly two
     *  arguments, if the first argument is not
     *  an instance of {@link Counter} or is not bigger than zero, or
     *  if the second argument is no instance of a {@link Formula}
     */
    public LeftAddition(final Argument[] arguments)
            throws ArgumentException {
        super (arguments);
        if (arguments.length != 2) {
            throw new ArgumentException(
                RuleConstants.CODE_CONSTRUCTOR_WRONG_ARGUMENT_NUMBER,
                RuleCreator.getName(this.getClass())
                + RuleConstants.OPERATOR_WITH_TWO_ARGUMENTS);
        }
        if (!(arguments[0] instanceof Counter)) {
            throw new ArgumentException(
                RuleConstants.CODE_CONSTRUCTOR_WRONG_ARGUMENT_TYPE,
                RuleCreator.getName(this.getClass())
                + RuleConstants.FIRST_ARGUMENT_TYPE
                + RuleConstants.NUMBER,
                arguments[0]);
        }
        this.n = ((Counter) arguments[0]).getNumber() - 1;
        if (n < 0) {
            throw new ArgumentException(
                RuleConstants.CODE_CONSTRUCTOR_WRONG_ARGUMENT_TYPE,
                RuleCreator.getName(this.getClass())
                + RuleConstants.FIRST_ARGUMENT_TYPE
                + RuleConstants.POSITIVE_INTEGER_EXPECTED,
                arguments[0]);
        }

        if (!(arguments[1] instanceof Formula)) {
            throw new ArgumentException(
                RuleConstants.CODE_CONSTRUCTOR_WRONG_ARGUMENT_TYPE,
                RuleCreator.getName(this.getClass())
                + RuleConstants.SECOND_ARGUMENT_TYPE
                + RuleConstants.FORMULA,
                arguments[1]);
        }
        this.additional = (Formula) arguments[1];
        // check if formula has no pattern variables
        if (additional.containsPatternVariables()) {
            throw new ArgumentException(
                RuleConstants.CODE_CONSTRUCTOR_WRONG_ARGUMENT_TYPE,
                RuleCreator.getName(this.getClass())
                + RuleConstants.SECOND_ARGUMENT
                + RuleConstants.NO_PATTERN_VARIABLE_ALLOWED,
                arguments[1]);
        }

    }


    /**
     * Check if proof could be extended with formula because of
     * left addition.
     *
     * @param   module   module
     * @param   proofLines  proof lines
     * @param   position number of proof lines that could be used
     *                    in the rule
     * @param   formula  formula to add
     * @throws  ArgumentException    if addition is not possible
     *          because the proof line numbers are not allowed (e.g.
     *          between 0 and the minimum of <code>position - 1</code>
     *          and current maximum proof line number)
     *          or the proof line number is no {@link Implication}
     *          or the implication and the additional formula have
     *           in common a subject variable that is bound in one
     *           formula and free in the other,
     *          or the resulting formula is not equal to
     *          <code>formula</code>
     *          or a version conflict occurs
     */
    public final void check(final Module module,
            final ProofLineList proofLines,
            final int position,
            final Formula formula) throws ArgumentException {

        if (version.greaterThan(module.getRuleVersion())) {
            throw new ArgumentException(
                RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                RuleCreator.getName(this.getClass())
                    + " " + RuleConstants.RULE_VERSION_CONFLICT
                    + version.getText(),
                this);
        }
        if (n < 0 || n >= proofLines.getArgumentSize() || n >= position) {
            throw new ArgumentException(
                RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                RuleCreator.getName(this.getClass())
                    + RuleConstants.PROOF_LINES_OUT_OF_RANGE,
                this.getArgument(0));
        }
        if (!(proofLines.getArgument(n).getArgument(0) instanceof Implication)) {
            throw new ArgumentException(
                RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                RuleCreator.getName(this.getClass())
                    + RuleConstants.PROOF_LINE_NO_IMPLICATION,
                this,
                proofLines.getArgument(n).getArgument(0));
        }
        final Implication impl = (Implication) proofLines
            .getArgument(n).getArgument(0);
        final Formula first = (Formula) impl.getArgument(0);
        final Formula second = (Formula) impl.getArgument(1);
        final Implication result;
        try {
            result = new Implication(
                new Disjunction(
                    additional,
                    first
                ),
                new Disjunction(
                    additional,
                    second
                )
            );
        } catch (ArgumentException e) {     // e.g. if variable
            throw new ArgumentException(    // is double bound
                RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                RuleCreator.getName(this.getClass())
                + RuleConstants.RIGHT_ADDITION_OF_FORMULA_NOT_POSSIBLE,
                this,
                proofLines.getArgument(n).getArgument(0));
        }
        if (!result.equals(formula)) {
            throw new ArgumentException(
                RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                RuleCreator.getName(this.getClass())
                    + RuleConstants.RESULT_NOT_EQUAL_WITH_EXPECTED,
                this,
                proofLines.getArgument(n).getArgument(0));
        }
    }


    /**
     * Return proof lines that could replace the proof line
     * <code>position</code>.
     *
     * @param   module      the belonging module
     * @param   proofLines  proof lines
     * @param   position    referenced proof line (starting with 0)
     *                       in <code>proofLines</code>
     * @return  proof lines that could substitute the single
     *           proof line <code>position</code>
     * @throws  IllegalArgumentException  if extension is impossible
     *           or other problems occured
     */
    public final ProofLineList extendWithout(final Module module,
            final ProofLineList proofLines, final int position)
            throws IllegalArgumentException {

        if (!this.equals(proofLines.getArgument(position)
                .getArgument(1))) {
            throw new IllegalArgumentException(
                "referenced proof line not equal with this one");
        }

        try {

            //  a => b                  (lineFormula)
            //  1. (c v a) => (c v b)   (formula1, ApplyAxiom/ApplySentence)

            //  a => b                  (lineFormula)
            final Formula lineFormula = (Formula) proofLines.getArgument(n)
                .getArgument(0);

            final ProofLineList newProofLines;
            try {
                newProofLines = new ProofLineList(new Argument[] {});
            } catch (ArgumentException e) {
                throw new IllegalArgumentException(e.toString());
            }

            //  1. (c v a) => (c v b)   (formula1, ApplyAxiom/ApplySentence)
            {
                final Formula formula1 = new Implication(
                    new Disjunction(
                        additional,
                        (Formula) lineFormula.getArgument(0)
                    ),
                    new Disjunction(
                        additional,
                        (Formula) lineFormula.getArgument(1)
                    )
                );
                final RuleDeclaration declaration = module.getRuleDeclaration(
                    this.getClass());

                final LinkReference reference
                    = (LinkReference) declaration.getArgument(2);
                final String label = reference.getReference();
                final Argument argument;
                try {
                    argument = module.getLabeledArgument(label);
                } catch (IllegalArgumentException e) {
                    throw new ArgumentException(
                        RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                        ParagraphCreator.getName(RuleDeclaration.class)
                            + " " + e.getMessage(),
                        reference.getArgument(0));
                }
                if (argument instanceof Sentence) {
                    newProofLines.add(
                        new ProofLine(new Argument[] {
                            formula1,
                            new ApplySentence(
                                new Argument[] {
                                    new Counter(this.n + 1),
                                    reference
                                }
                            )
                        }));
                } else {
                    newProofLines.add(
                        new ProofLine(new Argument[] {
                            formula1,
                            new ApplyAxiom(
                                new Argument[] {
                                    new Counter(this.n + 1),
                                    reference
                                }
                            )
                        }));
                }
            }

            return newProofLines;
        } catch (ArgumentException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }


    /** @inherited */
    public final int[] getProofLines() {
        return new int[] {this.n};
    }


    /** @inherited */
    public final Rule changeProofLines(final int[] mapping) {
        try {
            return (Rule) create(new Argument[] {
                new Counter(mapping[n] + 1), additional});
        } catch (ArgumentException e) {
            throw new IllegalArgumentException(e.toString());
        } catch (IndexOutOfBoundsException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }


    /**
     * Check if this rule could be declared.
     *
     * @param   module      the module context
     * @param   declaration the declaration that shall declare this rule
     * @throws  IllegalArgumentException    if an programming error occured
     * @throws  ArgumentException    if declaration failed
     */
    public final static void checkDeclaration(final Module module,
        final RuleDeclaration declaration) throws ArgumentException {
        if (declaration.getArgumentSize() != 3) {
            throw new ArgumentException(
                RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                ParagraphCreator.getName(RuleDeclaration.class)
                    + RuleConstants.OPERATOR_WITH_THREE_ARGUMENTS,
                declaration);
        }
        if (!(declaration.getArgument(2) instanceof LinkReference)) {
            throw new ArgumentException(
                RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                ParagraphCreator.getName(RuleDeclaration.class)
                + RuleConstants.THIRD_ARGUMENT_TYPE
                + RuleCreator.getName(LinkReference.class),
                declaration.getArgument(2));
        }
        {
            final LinkReference reference
                = (LinkReference) declaration.getArgument(2);
            final String label = reference.getReference();
            final Formula formula;
            try {
                formula = module.getLabeledFormula(label);
            } catch (IllegalArgumentException e) {
                throw new ArgumentException(
                    RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                    ParagraphCreator.getName(RuleDeclaration.class)
                        + " " + e.getMessage(),
                    reference.getArgument(0));
            }

            // this formula must be matched by the referenced one:
            // IMPL (
            //   IMPL (PROP(1), PROP(2)),
            //   IMPL (
            //     OR (PROP(3), PROP(1)),
            //     OR (PROP(3), PROP(2))
            //   )
            // )

            final Formula form =
                new Implication(
                    new Implication(
                        new PropositionVariable(1),
                        new PropositionVariable(2)
                    ),
                    new Implication(
                        new Disjunction(
                            new PropositionVariable(3),
                            new PropositionVariable(1)
                        ),
                        new Disjunction(
                            new PropositionVariable(3),
                            new PropositionVariable(2)
                        )
                    )
                );

            final Formula pattern = (Formula) AbstractFormula
                .createPattern(formula);
            if (!form.matches(pattern, new BasicPatternVariables())) {
                throw new ArgumentException(
                    RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                    ParagraphCreator.getName(RuleDeclaration.class)
                        + RuleConstants.RULE_DECLARATION_CONDITION_NOT_FULLFILLED,
                    reference.getArgument(0));
            }

            // check if ApplyAxiom or ApplySentence has been declared before
            final Argument argument;
            try {
                argument = module.getLabeledArgument(label);
            } catch (IllegalArgumentException e) {
                throw new ArgumentException(
                    RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                    ParagraphCreator.getName(RuleDeclaration.class)
                        + " " + e.getMessage(),
                    reference.getArgument(0));
            }
            if (argument instanceof Axiom
                    && !module.isRuleDeclared(ApplyAxiom.class)) {
                throw new ArgumentException(
                    RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                    RuleCreator.getName(ApplyAxiom.class)
                        + RuleConstants.RULE_DECLARATION_MISSING,
                    declaration.getArgument(0));
            } else if (argument instanceof Sentence
                    && !module.isRuleDeclared(ApplySentence.class)) {
                throw new ArgumentException(
                    RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                    RuleCreator.getName(ApplySentence.class)
                        + RuleConstants.RULE_DECLARATION_MISSING,
                    declaration.getArgument(0));
            }
        }
    }


    /** @inherited */
    public final Version getVersion() {
        return LeftAddition.version;
    }


    /** @inherited */
    public final Argument create(final Argument[] arguments)
            throws ArgumentException {
        return new LeftAddition(arguments);
    }


    /** @inherited */
    public final String toString() {
        return "LeftAddition " + getArgument(0) + " " + getArgument(1);
    }


}
