// $Id: HypotheticalSyllogism.java,v 1.12 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.Formula;
import com.meyling.principia.logic.basic.Implication;
import com.meyling.principia.logic.basic.PropositionVariable;
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 (pure) Hypothetical Syllogism:
 * <p>
 * <code> A1 => A2</code><p>
 * <code> A2 => A3</code><p>
 * <code>---------</code><p>
 * <code> A1 => A3</code><p>
 *
 * @version $Revision: 1.12 $
 * @author  Michael Meyling
 */
public class HypotheticalSyllogism 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;

    /** proof line of <code>A2 => A3</code>*/
    private final int m;


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


    /**
     * Constructs a hypothetical syllogism rule.
     *
     * @param   arguments    two line numbers to operate on
     *                       first argument must reference an implication
     *                       second argument must reference an implication
     *                       that has the second argoument of the
     *                       first referenced formula as
     *                       the first argument
     * @throws  ArgumentException    if there are not exactly two
     *          arguments that are instances of {@link Counter}
     *          or these arguments are not bigger than zero
     *
     */
    public HypotheticalSyllogism(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 Counter)) {
            throw new ArgumentException(
                RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                RuleCreator.getName(this.getClass())
                + RuleConstants.SECOND_ARGUMENT_TYPE
                + RuleConstants.NUMBER,
                arguments[1]);
        }
        this.m = ((Counter) arguments[1]).getNumber() - 1;
        if (m < 0) {
            throw new ArgumentException(
                RuleConstants.CODE_CONSTRUCTOR_WRONG_ARGUMENT_TYPE,
                RuleCreator.getName(this.getClass())
                + RuleConstants.SECOND_ARGUMENT_TYPE
                + RuleConstants.POSITIVE_INTEGER_EXPECTED,
                arguments[1]);
        }

    }


    /**
     * Check if proof could be extended with formula because of
     * hypothetical syllogism.
     *
     * @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 1 and the minimum of <code>position</code>
     *          and current maximum proof line number)
     *          or the refrenced proof lines are no {@link Implication}s
     *          or the first part formula of the second proof line
     *          is not equal to the second part formula of the
     *          first proof line
     *          or the implication made by the first part of the first
     *          formula and the second part of the second 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 (m < 0 || m >= proofLines.getArgumentSize() || m >= position) {
            throw new ArgumentException(
                RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                RuleCreator.getName(this.getClass())
                    + RuleConstants.PROOF_LINES_OUT_OF_RANGE,
                this.getArgument(1));
        }

        if (!(proofLines.getArgument(n).getArgument(0)
                instanceof Implication)) {
            throw new ArgumentException(
                RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                RuleCreator.getName(this.getClass())
                    + RuleConstants.FIRST_PROOF_LINE_NO_IMPLICATION,
                this,
                proofLines.getArgument(n).getArgument(0));
        }

        if (!(proofLines.getArgument(m).getArgument(0)
                instanceof Implication)) {
            throw new ArgumentException(
                RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                RuleCreator.getName(this.getClass())
                    + RuleConstants.SECOND_PROOF_LINE_NO_IMPLICATION,
                this,
                proofLines.getArgument(m).getArgument(0));
        }

        final Implication impl1 = (Implication) proofLines.getArgument(n)
            .getArgument(0);
        final Implication impl2 = (Implication) proofLines.getArgument(m)
            .getArgument(0);
        if (!impl1.getArgument(1).equals(impl2.getArgument(0))) {
            throw new ArgumentException(
                RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                RuleCreator.getName(this.getClass())
                    + RuleConstants.LAST_PART_FIRST_PART_NOT_EQUAL,
                this,
                impl2.getArgument(0));
        }
        final Implication result = new Implication(
            new Argument[] {impl1.getArgument(0), impl2.getArgument(1)});
        if (!result.equals(formula)) {
            throw new ArgumentException(
                RuleConstants.CODE_METHOD_ARGUMENT_CHECK_FAILED,
                RuleCreator.getName(this.getClass())
                    + RuleConstants.RESULT_NOT_EQUAL_WITH_EXPECTED,
                this);
        }
    }


    /**
     * 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                             (lineFormula1)
            //  b => c                             (lineFormula2)
            //  1. (x => y) => ((z => x) => (z => y)) (AddAxiom/AddSentence)
            //  2. (a => b) => ((c => a) => (c => b)) (formula2, SubstLine)
            //  3. (b => c) => ((a => b) => (a => c)) (formula3, SubstLine)
            //  4. (a => b) => (a => c)               (formula4, ModusPonens)
            //  5. a => c                             (formula5, ModusPonens)

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

            //  b => c                             (lineFormula2)
            final Formula lineFormula2 = (Formula) proofLines.getArgument(m)
                .getArgument(0);

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

            //  (x => y) => ((z => x) => (z => y)) (AddAxiom/AddSentence)
            {
                final RuleDeclaration declaration = module.getRuleDeclaration(
                    this.getClass());

                final String label
                    = ((LinkReference) declaration.getArgument(2)).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(),
                        declaration.getArgument(2).getArgument(0));
                }
                if (argument instanceof Sentence) {
                    newProofLines.add(
                        new ProofLine(new Argument[] {
                            argument.getArgument(0),
                            new AddSentence(
                                new Argument[] {
                                    declaration.getArgument(2)
                                }
                            )
                        }));
                } else {
                    newProofLines.add(
                        new ProofLine(new Argument[] {
                            argument.getArgument(0),
                            new AddAxiom(
                                new Argument[] {
                                    declaration.getArgument(2)
                                }
                            )
                        }));
                }
            }

            //  (a => b) => ((c => a) => (c => b)) (formula2, SubstLine)
            {
                final Formula formula2 = new Implication(
                    lineFormula1,
                    new Implication(
                        new Implication(
                            (Formula) lineFormula2.getArgument(1),
                            (Formula) lineFormula1.getArgument(0)
                        ),
                        new Implication(
                            (Formula) lineFormula2.getArgument(1),
                            (Formula) lineFormula1.getArgument(1)
                        )
                    )
                );
                newProofLines.add(
                    new ProofLine(
                        new Argument[] {
                            formula2,
                            new SubstLine(
                                new Argument[] {
                                    new Counter(position + 1)
                                }
                            )
                        }
                    )
                );
            }

            //  (b => c) => ((a => b) => (a => c)) (formula3, SubstLine)
            {
                final Formula formula3 = new Implication(
                    lineFormula2,
                    new Implication(
                        lineFormula1,
                        new Implication(
                            (Formula) lineFormula1.getArgument(0),
                            (Formula) lineFormula2.getArgument(1)
                        )
                    )
                );
                newProofLines.add(
                    new ProofLine(
                        new Argument[] {
                            formula3,
                            new SubstLine(
                                new Argument[] {
                                    new Counter(position + 1)
                                }
                            )
                        }
                    )
                );
            }

            //  (a => b) => (a => c)               (formula4, ModusPonens)
            {
                final Formula formula4 = new Implication(
                    lineFormula1,
                    new Implication(
                        (Formula) lineFormula1.getArgument(0),
                        (Formula) lineFormula2.getArgument(1)
                    )
                );
                newProofLines.add(
                    new ProofLine(
                        new Argument[] {
                            formula4,
                            new ModusPonens(
                                new Argument[] {
                                    new Counter(m + 1),
                                    new Counter(position + 3)
                                }
                            )
                        }
                    )
                );
            }

            //  a => c                             (formula5, ModusPonens)
            {
                final Formula formula5
                    = new Implication(
                        (Formula) lineFormula1.getArgument(0),
                        (Formula) lineFormula2.getArgument(1)
                    );
                newProofLines.add(
                    new ProofLine(
                        new Argument[] {
                            formula5,
                            new ModusPonens(
                                new Argument[] {
                                    new Counter(n + 1),
                                    new Counter(position + 4)
                                }
                            )
                        }
                    )
                );
                if (!formula5.equals(proofLines.getArgument(position)
                        .getArgument(0))) {
                    throw new IllegalArgumentException(
                        "expected result not equal to current");
                }
            }

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


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


    /** @inherited */
    public Rule changeProofLines(final int[] mapping) {
        try {
            return (Rule) create(new Argument[] {
                new Counter(mapping[n] + 1), new Counter(mapping[m] + 1)});
        } 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 String label
            = ((LinkReference) declaration.getArgument(2)).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(),
                declaration.getArgument(2).getArgument(0));
        }

        // IMPL (
        //   IMPL (PROP(1), PROP(2)),
        //   IMPL (
        //     IMPL (PROP(3), PROP(1)),
        //     IMPL (PROP(3), PROP(2))
        //   )
        // )

        final Formula form =
            new Implication(
                new Implication(
                    new PropositionVariable(1),
                    new PropositionVariable(2)
                ),
                new Implication(
                    new Implication(
                        new PropositionVariable(3),
                        new PropositionVariable(1)
                    ),
                    new Implication(
                        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,
                declaration.getArgument(2));
        }
    }


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


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


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


}
