﻿using AsmodeeDigital.PlayReal.Plugin.Manager.Persistence;
using AsmodeeDigital.PlayReal.Plugin.Network;
using System;
using UnityEngine;

namespace AsmodeeDigital.PlayReal.Plugin.Logic
{
    /// <summary>
    /// Abstract logic layer
    /// </summary>
    public abstract class LogicBase : ILogic
    {
        /// <summary>
        /// Persistent data
        /// </summary>
        public Persistence Persistence { get; set; }

        /// <summary>
        /// Unique communication component with DoW server
        /// </summary>
        public ServerConnection ServerConnection { get; set; }

        /// <summary>
        /// Enable the log system
        /// </summary>
        public bool LogEnabled { get; set; }

        /// <summary>
        /// Start log entry with time
        /// </summary>
        public bool LogWithTime { get; set; }

        /// <summary>
        /// Name for debug
        /// </summary>
        public String LogName { get; set; }

        public LogicBase(ServerConnection serverConnection, Persistence persistence)
        {
            ServerConnection = serverConnection;
            Persistence = persistence;

            LogEnabled = true;
            LogWithTime = false;
        }

        /// <summary>
        /// Log Exception
        /// </summary>
        /// <param name="ex"></param>
        public void Log(Exception ex)
        {
            Log(string.Format("{0}\r\n{1}", ex.Message, ex.StackTrace), LogType.Error);
        }

        /// <summary>
        /// Log standard message and raise event on client side
        /// </summary>
        /// <param name="message">Message to log</param>
        /// <param name="logType">Log type</param>
        public void Log(string message, LogType logType = LogType.Log)
        {
            if (!LogEnabled)
                return;

            string startMessage = string.Empty;

            if (LogWithTime)
                startMessage = String.Format("{0:HH:mm:ss} - ");

            if (!string.IsNullOrEmpty(LogName))
                startMessage += String.Format("{0} : ", LogName);

            switch (logType)
            {
                case LogType.Exception:
                case LogType.Error:
                    Debug.LogErrorFormat("{0}{1}", startMessage, message);
                    break;
                case LogType.Warning:
                    Debug.LogWarningFormat("{0}{1}", startMessage, message);
                    break;
                case LogType.Assert:
                case LogType.Log:
                    Debug.LogFormat("{0}{1}", startMessage, message);
                    break;

                default:
                    break;
            }
        }
    }
}
