using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace betrace_carfi_erp_driver.Common
{
    public static class Logger
    {
        public static ERPService mainForm = null;

        public static ERPService GetMainForm()
        {
            foreach (Form form in Application.OpenForms)
                if (form is ERPService)
                    return (ERPService)form;
            return null;
        }

        public static void WriteEntry(string message, EventLogEntryType type = EventLogEntryType.Information)
        {
            String strType = String.Empty;

            switch (type)
            {
                case EventLogEntryType.Information:
                    strType = "[INFO]"; 
                    break;
                case EventLogEntryType.Warning:
                    strType = "[WARNING]"; 
                    break;
                case EventLogEntryType.Error:
                    strType = "[ERROR]";
                    break;
            }

            writeOnDataGridViewLog(message, strType);

            try
            {
                string path = SystemInfo.LOGPATH == String.Empty ? ".\\log\\" : SystemInfo.LOGPATH;
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                if (!path.EndsWith("\\")) 
                    path = path + "\\";

                string logFile = path + DateTime.Now.ToString("yyyyMMdd") + ".txt";
                if (!File.Exists(logFile))
                {
                    File.Create(logFile);
                }

                using (StreamWriter w = File.AppendText(logFile))
                {
                    w.WriteLineAsync("\n" + DateTime.Now.ToString() + " - " + strType + " " + message);
                    w.Flush();
                }
            }
            catch (Exception ex)
            {
                string catchMessage = "An error occurred trying to write to the log file.\n";
                writeOnDataGridViewLog(catchMessage + ex.Message, "[ERROR]");
            }

        }
    
        public static void writeOnDataGridViewLog(String message, String type)
        {
            if (mainForm != null)
            {
                string[] row = new string[] { DateTime.Now.ToString(), type, message };
                mainForm.Invoke(new Action(() =>
                {
                    mainForm.dgvLog.Rows.Insert(0, row);

                    for (int i = mainForm.dgvLog.RowCount; i > 1000; i--) {
                        try
                        {
                            mainForm.dgvLog.Rows.RemoveAt(i);
                        }
                        catch (Exception)
                        { }
                    };

                }));
            }
        }
    }

}
