namespace MinicsConsole.Helper.RawDataFilter;

public class ChannelDataBaseHelper(byte mini8Index,ILog log) 
{
    private IORM? _orm;

    public void SetORM(IORM newOrm)
    {
        IORM? oldOrm = _orm;
        _orm = newOrm;
        oldOrm?.Dispose();
    }

    public void InsertDB_ChannelData(ChannelData channelData, Mini8Output mini8Output)
    {
        DBFormat _dbFormat = new();
        channelData.Adapt(_dbFormat);
        _dbFormat.DateTime = mini8Output.CollectTime;
        if (_orm?.Insert($"Mini8-{mini8Index}-{channelData.ChannelIndex}", _dbFormat) != true)
        {
            log.Error($"Mini8-{mini8Index}-{channelData.ChannelIndex} Write DB Failed");
            log.Error(JsonSerializer.Serialize(_dbFormat));
        }
    }

    public void InsertDB_TempAlarm(ChannelData channelData, Mini8Output mini8Output)
    {
        DBWarning warning = new()
        {
            ChannelIndex = mini8Output.ChannelIndex,
            DateTime = mini8Output.CollectTime,
            AlarmType = AlarmType.OverRange,
            PV = mini8Output.PV,
            Caps = channelData.Caps,
            Floor = channelData.Floor,
        };
        _orm?.Insert($"Error-Mini8-{mini8Index}", warning);
    }

    public void InsertDB_TcAlarm(ChannelData channelData, Mini8Output mini8Output)
    {
        DBWarning warning = new()
        {
            ChannelIndex = mini8Output.ChannelIndex,
            DateTime = mini8Output.CollectTime,
            AlarmType = AlarmType.SensorBrake,
            PV = mini8Output.PV,
            Caps = channelData.Caps,
            Floor = channelData.Floor,
        };
        _orm?.Insert($"Error-Mini8-{mini8Index}", warning);
    }


}