// Copyright (C) 2003, 2005 Daisuke Arai <darai@users.sourceforge.jp>
// Copyright (C) 2008, 2010, 2013 panacoran <panacoran@users.sourceforge.jp>
// 
// This program is part of Protra.
//
// Protra 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 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
// 
// $Id: FunctionNode.cs 472 2013-06-26 15:26:49Z panacoran $

using System;
using System.Collections.Generic;
using Protra.Lib.Lang.Builtins;

namespace Protra.Lib.Lang
{
    /// <summary>
    /// 関数のノードを表すクラス。
    /// </summary>
    public class FunctionNode : ExpressionNode
    {
        /// <summary>
        /// 関数のタイプ
        /// </summary>
        private FunctionType _functionType;

        /// <summary>
        /// 引数のノードのリスト
        /// </summary>
        private readonly List<ExpressionNode> _nodeList = new List<ExpressionNode>();

        /// <summary>
        /// 構文解析する。
        /// </summary>
        /// <exception cref="Protra.Lib.Lang.ParseException">
        /// 構文解析中にエラーが発生したときにthrowされる。
        /// </exception>
        /// <return>
        /// 解析した結果のノード。
        /// </return>
        public override ExpressionNode Parse(Scanner scanner)
        {
            Token = scanner.Token;

            // 関数名の取得
            var name = scanner.Token.Value;

            // 引数のチェック
            scanner.Scan();
            if (scanner.Token.Value != "(")
            {
                _functionType = new FunctionType(name, 0);
                return this;
            }
            scanner.Scan();
            if (scanner.Token.Value == ")")
            {
                _functionType = new FunctionType(name, 0);
                scanner.Scan();
                return this;
            }
            do
            {
                _nodeList.Add(new ExpressionNode().Parse(scanner));
                if (scanner.Token.Value == ")")
                {
                    _functionType = new FunctionType(name, _nodeList.Count);
                    scanner.Scan();
                    return this;
                }
                if (scanner.Token.Value != ",")
                    throw new ParseException("',' or ')' expected", Token);
            } while (scanner.Scan());
            throw new ParseException("unexpected EOF", Token);
        }

        /// <summary>
        /// 式を評価する。
        /// </summary>
        /// <exception cref="Protra.Lib.Lang.RuntimeException">
        /// 評価中にエラーが発生した場合にthrowされる。
        /// </exception>
        /// <param name="resource">リソース</param>
        /// <param name="at">int型@作用素の値</param>
        /// <param name="ats">string型@作用素の値</param>
        /// <returns>値</returns>
        public override Value Evaluate(Resource resource, int at, string ats)
        {
            // 関数が定義されていれば実行する
            if (resource.FunctionTable.ContainsKey(_functionType))
            {
                // 関数定義ノードの取得
                var fdn = resource.FunctionTable[_functionType];

                // 記号表を用意
                var variables = new Dictionary<string, Value>();
                variables["at"] = new Value(at);
                for (var i = 0; i < _nodeList.Count; i++)
                    variables[fdn.Arguments[i]] = _nodeList[i].Evaluate(resource, at, ats);
                resource.Stack.Push(variables);

                // 文の実行
                foreach (var node in fdn.Nodes)
                {
                    switch (node.Execute(resource, at, ats))
                    {
                        case ExecutableNode.Result.Normal:
                            break;
                        case ExecutableNode.Result.Return:
                            resource.Stack.Pop();
                            return resource.ReturnValue;
                        case ExecutableNode.Result.Confinue:
                            throw new RuntimeException("unexpected continue", resource.Token);
                        case ExecutableNode.Result.Break:
                            throw new RuntimeException("unexpected break", resource.Token);
                    }
                }
                resource.Stack.Pop();
                return null;
            }

            // 組み込み関数を実行する。
            try
            {
                var args = new Value[_nodeList.Count];
                for (var i = 0; i < _nodeList.Count; i++)
                {
                    var node = _nodeList[i];
                    args[i] = node.Evaluate(resource, at, ats);
                }
                return resource.Builtins.Invoke(_functionType.Name, args, at, ats);
            }
            catch (NoSuchBuiltinException e)
            {
                throw new RuntimeException("undefined function --- " + _functionType, Token, e);
            }
            catch (InvalidCastException e)
            {
                throw new RuntimeException("wrong type argument for " + _functionType, Token, e);
            }
            catch (NullReferenceException e)
            {
                throw new RuntimeException("null argument for " + _functionType, Token, e);
            }
            catch (Exception e)
            {
                throw new RuntimeException(e.Message, Token, e);
            }
        }
    }
}