using System;
using System.IO;
using UnityEngine;

namespace RothenburgAR.Common
{
    public class LogFileHandler : ILogHandler
    {
        private StreamWriter m_StreamWriter;
        private ILogHandler m_DefaultLogHandler = Debug.unityLogger.logHandler;

        public LogFileHandler()
        {
            string logFileDirectory = Path.Combine(Application.persistentDataPath, "logs");
            if (!Directory.Exists(logFileDirectory))
                Directory.CreateDirectory(logFileDirectory);

            DeleteOldLogs();

            string date = DateTime.Now.ToString("yyyy-MM-dd.hh-mm-ss");
            string filePath = Path.Combine(logFileDirectory, date + ".log.txt");

            var m_FileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            m_StreamWriter = new StreamWriter(m_FileStream);

            // Replace the default debug log handler
            Debug.unityLogger.logHandler = this;
        }

        private void DeleteOldLogs()
        {
            string logFileDirectory = Path.Combine(Application.persistentDataPath, "logs");

            var numberOfFilesToKeep = 30;
            var filePaths = Directory.GetFiles(logFileDirectory);
            for (var n = 0; n < filePaths.Length - numberOfFilesToKeep; n++)
            {
                File.Delete(filePaths[n]);
            }
        }

        public void LogFormat(LogType logType, UnityEngine.Object context, string format, params object[] args)
        {
            var sDate = DateTime.Now.ToString("ddd dd-MM-yyyy hh:mm:ss");
            var prefix = sDate + " - " + logType.ToString() + " :: ";


            m_StreamWriter.WriteLine(String.Format(prefix + format, args));
            m_StreamWriter.Flush();


            var color = getColorByLogType(logType);
            string newFormat = format;
            if (color != null)
            {
                newFormat = prefix + "<color=" + color + ">" + format + "</color>";
            }

            m_DefaultLogHandler.LogFormat(logType, context, newFormat, args);
        }

        private string getColorByLogType(LogType logType)
        {
            switch (logType)
            {
                case LogType.Assert:
                    return "yellow";
                case LogType.Error:
                case LogType.Exception:
                    return "red";
                case LogType.Warning:
                    return "orange";
                case LogType.Log:
                default:
                    return null;
            }
        }

        public void LogException(Exception exception, UnityEngine.Object context)
        {
            m_DefaultLogHandler.LogException(exception, context);
        }
    }
}
