using System;
using System.IO;

namespace HyperCube.Utils
{
    public static class AdvConsole
    {
        private const string LOGS_FOLDER = "Logs";
        //private const string LOGS_ARCHIVE_FOLDER = "Archives";
        private const string LOG_FILE_NAME = "current.log";

        static StreamWriter _writer;
        static TextWriter _oldOut = Console.Out;

        static string _folderPath;
        static string _fullPath;

        public static void Initialize()
        {
            _folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, LOGS_FOLDER);
            _fullPath = Path.Combine(_folderPath, LOG_FILE_NAME);
            _oldOut = Console.Out;

            if (File.Exists(_fullPath))
                File.Move(_fullPath, Path.Combine(_folderPath, $"{DateTime.Now:yyyy.MM.dd_HH-mm-ss}.log"));
        }

        public static void WriteLine(string message)
        {   
            try
            {
                if (!Directory.Exists(_folderPath))
                    Directory.CreateDirectory(_folderPath);

                if (File.Exists(_fullPath))
                    _writer = File.AppendText(_fullPath);
                else
                    _writer = File.CreateText(_fullPath);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Cannot open [{_fullPath}] for writing");
                Console.WriteLine(e.Message);
                return;
            }
            string fullmessage = $"{DateTime.Now:yyyy.MM.dd HH:mm:ss.fff}: {message}";
            Console.SetOut(_writer);
            Console.WriteLine(fullmessage);
            Console.SetOut(_oldOut);
            Console.WriteLine(fullmessage);
            _writer.Close();
        }       
    }
}
