using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;

namespace FormulaEditor
{
    /// <summary>
    /// Performer of derivations
    /// </summary>
    public class DerivationPerformer
    {

        /// <summary>
        /// Calculates derivation
        /// </summary>
        /// <param name="tree">Tree to calculate</param>
        /// <returns></returns>
        static public ObjectFormulaTree Derivation(ObjectFormulaTree tree, string s)
        {
            if (tree.Operation is IDerivationOperation)
            {
                IDerivationOperation op = tree.Operation as IDerivationOperation;
                return op.Derivation(tree, s);
            }
            if (ElementaryBinaryOperation.IsInteger(tree.Operation.ReturnType))
            {
                ElementaryRealConstant op = new ElementaryRealConstant(0);
                return new ObjectFormulaTree(op, new List<ObjectFormulaTree>());
            }
            if (tree.Operation is OptionalOperation)
            {
                OptionalOperation op = tree.Operation as OptionalOperation;
                op = op.Clone() as OptionalOperation;
                List<ObjectFormulaTree> list = new List<ObjectFormulaTree>();
                list.Add(tree[0].Clone() as ObjectFormulaTree);
                for (int i = 1; i < 3; i++)
                {
                    list.Add(DerivationPerformer.Derivation(tree[i], s));
                }
                return new ObjectFormulaTree(op, list);
            }
            return null;
        }
    }
}
