/*
 * Source.cs --
 *
 * Copyright (c) 2007-2012 by Joe Mistachkin.  All rights reserved.
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * RCS: @(#) $Id: $
 */

using System.Text;
using Eagle._Attributes;
using Eagle._Components.Public;
using Eagle._Constants;
using Eagle._Containers.Public;
using Eagle._Interfaces.Public;

namespace Eagle._Commands
{
    [ObjectId("076f3c98-c556-4145-aba5-5aa440040581")]
    /*
     * POLICY: We allow files in the script library directory to be sourced.
     */
    [CommandFlags(CommandFlags.Unsafe | CommandFlags.Standard)]
    [ObjectGroup("engine")]
    internal sealed class Source : Core
    {
        public Source(
            ICommandData commandData
            )
            : base(commandData)
        {
            // do nothing.
        }

        #region IExecute Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count >= 2)
                    {
                        OptionDictionary options = new OptionDictionary(
                            new Option[] { 
                            new Option(null, OptionFlags.MustHaveValue, Index.Invalid, Index.Invalid, "-encoding", null),
                            new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null)
                        });

                        int argumentIndex = Index.Invalid;

                        if (arguments.Count > 2)
                        {
                            code = interpreter.GetOptions(options, arguments, 0, 1, Index.Invalid, false, ref argumentIndex, ref result);
                        }
                        else
                        {
                            argumentIndex = 1;
                            code = ReturnCode.Ok;
                        }

                        if (code == ReturnCode.Ok)
                        {
                            if ((argumentIndex != Index.Invalid) && ((argumentIndex + 1) == arguments.Count))
                            {
                                Variant value = null;
                                string encodingName = null;

                                if (options.IsPresent("-encoding", ref value))
                                    encodingName = value.ToString();

                                Encoding encoding = null;

                                if (encodingName != null)
                                {
                                    code = Interpreter.GetEncoding(
                                        interpreter, encodingName, ref encoding, ref result);
                                }

                                if (code == ReturnCode.Ok)
                                {
                                    string name = StringList.MakeList("source", arguments[argumentIndex]);

                                    ICallFrame frame = interpreter.NewTrackingCallFrame(name,
                                        CallFrameFlags.Source);

                                    interpreter.PushAutomaticCallFrame(frame);

                                    code = interpreter.EvaluateFile(encoding, arguments[argumentIndex], ref result);

                                    //
                                    // NOTE: Pop the original call frame that we pushed above and 
                                    //       any intervening scope call frames that may be leftover 
                                    //       (i.e. they were not explicitly closed).
                                    //
                                    /* IGNORED */
                                    interpreter.PopCallFrame(CallFrameFlags.Scope, true);
                                }
                            }
                            else
                            {
                                if ((argumentIndex != Index.Invalid) &&
                                    Option.LooksLikeOption(arguments[argumentIndex]))
                                {
                                    result = OptionDictionary.BadOption(options, arguments[argumentIndex]);
                                }
                                else
                                {
                                    result = "wrong # args: should be \"source ?-encoding name? fileName\"";
                                }

                                code = ReturnCode.Error;
                            }
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"source ?-encoding name? fileName\"";
                        code = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code = ReturnCode.Error;
            }

            return code;
        }
        #endregion
    }
}
