using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Text.RegularExpressions;

namespace SCAN.lib
{
    class Utils
    {
        static LogWriter logger = LogWriter.getInstance();

        public static List<FileInfo> listFile(string dir, string search)
        {
            List<FileInfo> items = new List<FileInfo>();
            DirectoryInfo d = new DirectoryInfo(dir);
            foreach (FileInfo file in d.GetFiles(search))
            {
                items.Add(file);
            }
            return items;
        }

        public static void removeDirectory(string dir, bool remove_dir)
        {
            try
            {
                DirectoryInfo di = new DirectoryInfo(dir);

                foreach (FileInfo file in di.GetFiles())
                {
                    file.Delete();
                }
                if (remove_dir)
                    foreach (DirectoryInfo d in di.GetDirectories())
                    {
                        d.Delete(true);
                    }
            }
            catch (DirectoryNotFoundException ex)
            {
                logger.Log(String.Format("Error: {0}[{1}]", ex.Message, dir)); 
            }
        }

        public static void removeFile(string file)
        {
            try
            {
                FileInfo fi = new FileInfo(file);

                fi.Delete();
            }
            catch (FileNotFoundException ex)
            {
                logger.Log(String.Format("Error: {0}[{1}]", ex.Message, file));
            }
        }

        public static void mkdir(string dir)
        {
            Directory.CreateDirectory(dir);
        }

        public static List<string> regexPattern(string input, string pattern)
        {
            List<string> output = new List<string>();
            MatchCollection matches = Regex.Matches(input, pattern, RegexOptions.IgnoreCase);
            object[] words = new object[1024];

            int index = 0;
            foreach (Match match in matches)
            {
                match.Groups.CopyTo(words, index);
                index += 2;
            }

            // Display captured groups.
            for (int ctr = 1; ctr <= words.GetUpperBound(0); ctr += 2)
            {
                if (words[ctr] == null)
                    break;
                output.Add(words[ctr].ToString());
            }

            return output;
        }

        public static string getCsvFormatString(int cols)
        {
            string tmp = "";
            for (int i = 0; i < cols; i++)
            {
                tmp += (i > 0 ? "," : "") + "\"{" + i + "}\""; 
            }

            return tmp;
        }

        public static bool isDigit(string str)
        {
            string pattern = @"^[\d]+$";
            Match match = Regex.Match(str, pattern);
            return match.Success;
        }
    }
}
