/*
 * This work is licensed unde the MIT License (MIT)
 * Copyright (c) 2020-2021 (overlord)
 * https://opensource.org/licenses/MIT
 */
using System;
using System.Numerics;
using System.Collections.Generic;

using SMath.Manager;
using SMath.Math;

namespace BigIntegerArithmetics.SMathFunctions
{
    /// <summary>
    /// Divides two big integers written as strings.
    /// </summary>
    public static class bigDiv
    {
        public static string SMathFunctionName = "bigDiv";

        public static TermInfo GetTermInfo()
        {
            return new TermInfo (
                SMathFunctionName,
                TermType.Function,
                "Divide \"1:integer\" to another \"2:integer\" written as strings.",
                FunctionSections.Unknown,
                true,
                new ArgumentInfo(ArgumentSections.String),
                new ArgumentInfo(ArgumentSections.String)
               ){ IsUndefinedArgumentsSupported = true };
        }

        public static bool IsSupport(Term root)
        {
            if (root.ArgsCount == 2 && root.Text == SMathFunctionName)
                return true;

            return false;
        }

        public static bool ExpressionEvaluation(Term root, Term[][] args, ref Store store, ref Term[] result)
        {
            Term[]
                arg1 = Computation.Preprocessing(args[0], ref store),
                arg2 = Computation.Preprocessing(args[1], ref store);

            result = DivIntegers(arg1, arg2, store);

            return true;
        }

        public static Term[] DivIntegers(Term[] int1, Term[] int2, Store store)
        {
            if (int1.Length > 1 || int2.Length > 1 || !int1[0].Text.StartsWith(Symbols.StringChar) || !int2[0].Text.StartsWith(Symbols.StringChar))
                throw new GeneralException(Errors.ArgumentMustBeString);
            BigInteger num1 = BigInteger.Parse(int1[0].Text.Substring(1, int1[0].Text.Length - 2));
            BigInteger num2 = BigInteger.Parse(int2[0].Text.Substring(1, int2[0].Text.Length - 2));
            return new[] { new Term(Symbols.StringChar + BigInteger.Divide(num1, num2).ToString() + Symbols.StringChar, TermType.Operand, 0) };
        }
    }
}