namespace MinicsConsole.Connector;

public class LogSender(BasicInfo basicInfo) : SenderBase_SignalR, ILog
{
    private ILog? _log;

    public string? Directory { get; internal set; }
    public string? FilePath { get; internal set; }

    private string? _FileName;

    bool ILog.Initialize(string fileName)
    {
        this._log ??= new Logger.Logger();
        _log.Initialize(fileName);
        this.Directory = _log.Directory;
        this._FileName = fileName;
        return true;
    }

    //Switch to new log file path and clean old files before basicInfo.DBKeepRange
    public bool CleanLog()
    {
        ILog log = new Logger.Logger();
        log.Initialize(_FileName!);

        ILog? oldLog = this._log;
        this._log = log;

        if (oldLog is null)
            return false;

        if (string.IsNullOrEmpty(oldLog.Directory) ||
            !DierctoryHelper.GetAllFiles(oldLog.Directory, out List<FileInfo>? files) ||
            files is null)
            goto Finallizer;

        foreach (FileInfo file in files)
        {
            if (file.CreationTime >= DateTime.Now.AddDays(-basicInfo.DBKeepRange))
                continue;

            try
            {
                File.Delete(file.FullName);
            }
            catch
            {

            }
        }

    Finallizer:
        oldLog?.Dispose();
        this.Directory = this._log.Directory;
        return true;
    }

    bool ILog.Debug(string message, DateTime? dateTime)
    {
        dateTime ??= DateTime.Now;
        _log?.Debug(message, dateTime);
        return this.SendAll("Debug", message, dateTime);
    }

    bool ILog.Error(string message, DateTime? dateTime)
    {
        dateTime ??= DateTime.Now;
        _log?.Error(message, dateTime);
        return this.SendAll("Error", message, dateTime);
    }

    bool ILog.Fatal(string message, DateTime? dateTime)
    {
        dateTime ??= DateTime.Now;
        _log?.Fatal(message, dateTime);
        MessageBox.Show(message, "Fatal", MessageBoxButton.OK, MessageBoxImage.Stop);
        return this.SendAll("Fatal", message, dateTime);
    }

    bool ILog.Info(string message, DateTime? dateTime)
    {
        dateTime ??= DateTime.Now;
        _log?.Info(message, dateTime);
        return this.SendAll("Info", message, dateTime);
    }

    bool ILog.Warning(string message, DateTime? dateTime)
    {
        dateTime ??= DateTime.Now;
        _log?.Warning(message, dateTime);
        return this.SendAll("Warning", message, dateTime);
    }

    public void Dispose()
    {
        this._log?.Dispose();
    }
}