// Created with MonoDevelop
//
//    Copyright (C) 2022, Germany
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.


using System;
using Hiperscan.Common.LogWriter;

namespace Hiperscan.Common
{
    public class MemoryCleaner
    {
        public MemoryCleaner(long intervall, int slepp_time_in_ms)
        {
            this.SleepTime = slepp_time_in_ms;
            this.Internvall = intervall;
        }

        public void Clean()
        {
            lock (this.Sync)
            {
                if (this.Count % this.Internvall == 0 || this.Count == this.TotalCount)
                {
                    if (this.Count != 0)
                    {
                        GC.Collect();
                        GC.WaitForPendingFinalizers();
                        System.Threading.Thread.Sleep(this.SleepTime);
                    }

                    this.WriteConsoleOutput();
                }

                this.Count++;
            }
        }

        private void WriteConsoleOutput()
        {
            if (this.Quiet == true)
                return;

            if (String.IsNullOrEmpty(this.OutputFormat))
            {
                Console.WriteLine($"Memory cleaner called after {this.Count} units.");
                return;
            }

            Console.WriteLine(this.OutputFormat, this.Count, this.TotalCount);
        }

        private object Sync { get; set; } = new object();

        private long Count { get; set; } = 0;
        public long Internvall { get; private set; }
        public int SleepTime { get; private set; }

        public bool Quiet { get; set; }
        public string OutputFormat { get; set; }
        public long TotalCount { get; set; }
    }

}
