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

namespace lib
{
    class Utils
    {

        public static Dictionary<string, string> parseArrayData(Dictionary<string, string> cols, string[] data)
        {
            int i = 0;
            foreach (KeyValuePair<string, string> col in cols)
            {
                cols[col.Key] = data[i++];
            }

            return cols;
        }

        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 Boolean isDigit(String str)
        {
            
            return Regex.IsMatch(str, @"[\d]{16}");
        }

        /*

        public static void ConvertCsvToExcel(string csvFilePath, string excelOutputFile = null)
        {
            // prepare output filename, replace csv => xlsx if omitted
            if (excelOutputFile == null)
            {
                excelOutputFile = csvFilePath.Replace(".csv", ".xlsx");
            }

            List<string[]> csv_rows = new List<string[]>();
            StreamReader streamReader = new StreamReader(csvFilePath);
            string line;
            while ((line = streamReader.ReadLine()) != null)
            {
                List<String> strList = lib.CsvParser.Parse(line);
                csv_rows.Add(strList.ToArray());
            }


            using (var p = new OfficeOpenXml.ExcelPackage())
            {
                var sheet = p.Workbook.Worksheets.Add("Sheet1");

                for (int i = 0; i < csv_rows.Count; i++)
                {
                    for (int j = 0; j < csv_rows[i].Count(); j++)
                    {
                        sheet.Cells[i + 1, j + 1].Value = csv_rows[i][j];
                    }
                }

                p.SaveAs(new FileInfo(excelOutputFile));

            }
        }

        public static int ConvertExcelToCsv(string excelFilePath, string csvOutputFile, bool firstline_exclude, int worksheetNumber)
        {
            int process_line = 0;
            if (!File.Exists(excelFilePath)) throw new FileNotFoundException(excelFilePath);
            if (File.Exists(csvOutputFile)) throw new ArgumentException("File exists: " + csvOutputFile);

            List<string[]> rows = new List<string[]>();
            FileInfo fi = new FileInfo(excelFilePath);
            using (var package = new ExcelPackage(fi))
            {
                //get the first worksheet in the workbook
                ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                int colCount = worksheet.Dimension.End.Column;  //get Column Count
                int rowCount = worksheet.Dimension.End.Row;     //get row count
                for (int row = 1; row <= rowCount; row++)
                {
                    string[] cols = new string[colCount];
                    for (int col = 1; col <= colCount; col++)
                    {
                        //
                        try
                        {
                            cols[col - 1] = worksheet.Cells[row, col].Value.ToString().Trim();
                        }
                        catch (Exception ex)
                        {
                            cols[col - 1] = (string) worksheet.Cells[row, col].Value;
                        }
                    }
                    KJT.frm._main_form.log(String.Join(",", cols));
                    rows.Add(cols);
                }
            }

            // write out CSV data
            using (var wtr = new StreamWriter(csvOutputFile))
            {
                foreach (string[] row in rows)
                {
                    if (firstline_exclude)
                    {
                        firstline_exclude = false;
                        continue;
                    }
                    bool firstLine = true;
                    foreach (string col in row)
                    {
                        if (!firstLine) { wtr.Write(","); } else { firstLine = false; }
                        if (col != null)
                        {
                            var data = col.Replace("\"", "\"\"");
                            wtr.Write(String.Format("\"{0}\"", data));
                        }
                    }
                    process_line++;
                    wtr.WriteLine();
                }
            }

            return process_line;
        }

        public static List<String> ParseExcel(string excelFilePath, bool firstline_exclude, int worksheetNumber) {
            List<String> csvList = null;
            if (!File.Exists(excelFilePath)) throw new FileNotFoundException(excelFilePath);

            List<string[]> rows = new List<string[]>();
            FileInfo fi = new FileInfo(excelFilePath);
            using (var package = new ExcelPackage(fi))
            {
                //get the first worksheet in the workbook
                ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                int colCount = worksheet.Dimension.End.Column;  //get Column Count
                int rowCount = worksheet.Dimension.End.Row;     //get row count
                for (int row = 1; row <= rowCount; row++)
                {
                    string[] cols = new string[colCount];
                    for (int col = 1; col <= colCount; col++)
                    {
                        cols[col - 1] = worksheet.Cells[row, col].Value.ToString().Trim();
                    }
                    KJT.frm._main_form.log(String.Join(",", cols));
                    rows.Add(cols);
                }
            }

            // write out CSV data
            csvList = new List<String>();
            foreach (string[] row in rows)
            {
                if (firstline_exclude)
                {
                    firstline_exclude = false;
                    continue;
                }
                bool firstLine = true;
                StringBuilder cols = new StringBuilder();
                foreach (string col in row)
                {
                    if (!firstLine) { cols.Append(","); } else { firstLine = false; }
                    var data = col.Replace("\"", "\"\"");
                    cols.Append(String.Format("\"{0}\"", data));
                }
                csvList.Add(cols.ToString());
            }

            return csvList;
        }
        */

        static Random random = new Random();
        public static string GetRandomHexNumber(int digits=16)
        {
            byte[] buffer = new byte[digits / 2];
            random.NextBytes(buffer);
            string result = String.Concat(buffer.Select(x => x.ToString("X2")).ToArray());
            if (digits % 2 == 0)
                return result;
            return result + random.Next(16).ToString("X");
        }
    }
}
