//>>> _using
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpDX;
using SharpDX.Direct3D11;
using SharpDX.Windows;
//<<< _using

using System.IO;
using System.Dynamic;
using System.Text.RegularExpressions;

namespace Framefield.Core.IDc593c7f5_15b3_4196_a30d_01adf8ab7445
{
    public class Class_FilesInDirectory : OperatorPart.Function
    {
        //>>> _inputids
        private enum InputId
        {
            DirectoryPath = 0,
            Match = 1
        }
        //<<< _inputids

        //>>> _outputids
        private enum OutputId
        {
            Dynamic = 0,
            Count = 1
        }
        //<<< _outputids

        public override OperatorPartContext Eval(OperatorPartContext context, List<OperatorPart> inputs, int outputIdx) {
            //>>> _params
            var DirectoryPath = inputs[(int)InputId.DirectoryPath].Eval(context).Text;
            var Match = inputs[(int)InputId.Match].Eval(context).Text;
            //<<< _params


            if( DirectoryPath != _directoryPath || Match != _matchString) {
                _list = new List<string>();
                _directoryPath = DirectoryPath;
                _matchString = Match;
    
                try
                {

                    _list.AddRange(from filename in Directory.GetFiles(DirectoryPath) 
                                  let basename = filename.Split('\\').Last() 
                                  where Regex.Match(basename, Match, RegexOptions.IgnoreCase).Success 
                                  select filename);
                }
                

                catch (DirectoryNotFoundException)
                {
                    Logger.Warn("Cound not read directory '{0}'", DirectoryPath);
                }
                catch (ArgumentException)
                {
                    Logger.Warn("Invalid directory path '{0}'", DirectoryPath);
                }
                catch
                {
                    Logger.Warn("could not acces directory path '{0}'", DirectoryPath);
                }
            }
            
            switch(outputIdx) {
                case  (int)OutputId.Dynamic:
                    context.Dynamic = _list;
                    break;
                case  (int)OutputId.Count:
                    context.Value = _list.Count;    // FIXME: This is never called?
                    break;
            }
            context.Value = _list.Count;
            return context;
            
         
        }
        
        private string _directoryPath;
        private string _matchString;
        private List<string> _list = new List<string>();
        
    }
}

