using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FiscalPrinterSDK
{
    public static class LogComm
    {
        private static string filePath = "";
        private static string fileName = "";
        private static int maxRows = 0;
        private static List<string> fileLines = new List<string>();
        public static void SetParams(string path,string Name,int rowLimit)
        {
            filePath = path;
            fileName = Name;
            maxRows = rowLimit;
        }

        public static bool HasWriteAccessToFolder(string folderPath)
        {
            try
            {
                // Attempt to get a list of security permissions from the folder. 
                // This will raise an exception if the path is read only or do not have access to view the permissions. 
                System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(folderPath);
                return true;
            }
            catch (UnauthorizedAccessException)
            {
                return false;
            }
        }

        private static int lineCount = 0;
        public static void Log(string line)
        {
            try
            {
                var fullPath = filePath + "\\" + fileName;
                if (!Directory.Exists(filePath))
                {
                    var r = Directory.CreateDirectory(filePath);
                    if (!HasWriteAccessToFolder(filePath)) return;
                }
                if (fileLines.Count < 1)
                {
                    if (File.Exists(fullPath))
                    {
                        lineCount = File.ReadLines(fullPath).Count();
                        fileLines.AddRange(File.ReadLines(fullPath));
                    }
                }
                if (fileLines.Count>= maxRows)
                
                {
                   
                    var toRemove = Math.Max(1, (lineCount * 0.1) / 100);
                    for (int i = 0; i < toRemove; i++)
                    {
                        fileLines.RemoveAt(0);
                    }
                    
                }
               
                File.WriteAllLines(fullPath, fileLines);
                fileLines.Add(line);
                File.AppendAllText(fullPath, line + Environment.NewLine);

            }
            catch(Exception)
            {
                throw;
            }
        }
    }
}
