using FreeRedis;

namespace WCS.Core;

public class VitrualRedisPLC : IPLCAccessor
{
    private readonly int dbLen = 50000;
    private readonly PLCInfo plcInfo;
    private readonly RedisClient redis;

    public VitrualRedisPLC(PLCInfo plcInfo, string redisConnStr)
    {
        this.plcInfo = plcInfo;
        redis = new RedisClient(redisConnStr);
    }

    public byte[] ReadBytes(ushort db, ushort address, ushort length)
    {
        var key = $"{plcInfo.IP}-{db}";
        if (!redis.Exists(key)) redis.SetRange(key, 0, new byte[dbLen]);

        var res = redis.GetRange<byte[]>(key, address, address + length - 1);
        return res;
    }

    public void WriteBytes(ushort db, ushort address, byte[] data)
    {
        var key = $"{plcInfo.IP}-{db}";
        if (!redis.Exists(key)) redis.SetRange(key, 0, new byte[dbLen]);
        redis.SetRange(key, address, data);
    }
}