namespace MinicsConsole.Helper;

public class DataBaseCleaner(BasicInfo basicInfo, OrmCollections ormCollections, Hardwares hardwares, ILog log)
{
    public bool CleanDB()
    {
        if (ormCollections.MainORM is null)
            return false;
        DateTime clearSince = DateTime.Now.AddDays(basicInfo.DBKeepRange * (-1));
        foreach (KeyValuePair<byte, ConcurrentDictionary<byte, ChannelData>> mini8_channel in hardwares.Mini8Channels)
        {
            byte mini8Index = mini8_channel.Key;
            try
            {
                if (!ormCollections.MainORM.Delete<DBWarning>($"Error-Mini8-{mini8Index}", dbData => dbData.DateTime < clearSince))
                    log.Warning($"DB Clean before {clearSince:yyyy-MM-dd HH:mm:ss} - Warning History Mini8{mini8Index}");

                log.Info($"DB Clean before {clearSince:yyyy-MM-dd HH:mm:ss} - Warning History Mini8{mini8Index}");
            }
            catch
            {
                log.Warning($"DB Clean before {clearSince:yyyy-MM-dd HH:mm:ss}- Warning History Mini8{mini8Index}");
            }

            foreach (KeyValuePair<byte, ChannelData> channel in mini8_channel.Value)
            {
                try
                {
                    if (!ormCollections.MainORM.Delete<DBFormat>($"Mini8-{mini8Index}-{channel.Key}", dbData => dbData.DateTime < clearSince))
                        log.Warning($"DB Clean - Mini8 History Mini8{mini8Index}-{channel.Key}");
                    log.Info($"DB Clean before {clearSince:yyyy-MM-dd HH:mm:ss} - Mini8 History Mini8{mini8Index}-{channel.Key}");
                }
                catch
                {
                    log.Warning($"DB Clean before {clearSince:yyyy-MM-dd HH:mm:ss} - Mini8 History Mini8{mini8Index}-{channel.Key}");
                }
            }
        }

        basicInfo.DBClearTime = DateTime.Now;
        BaseConfigFileLoader.Save(basicInfo);
        return true;
    }
}
