package modbus

import (
	"fmt"
	"io"

	"git.simanc.com/software/golib/v4/gnet"
)

func ReadRegisterFrom(r io.Reader, register, quantity int) ([]byte, error) {
	start := register * 2
	if quantity == 0 {
		quantity = 1
	}
	length := quantity * 2

	// 跳过前面的字节
	if start > 0 {
		if seeker, ok := r.(io.Seeker); ok {
			_, err := seeker.Seek(int64(start), io.SeekStart)
			if err != nil {
				return nil, fmt.Errorf("failed to seek: %v", err)
			}
		} else {
			// 如果不支持 seek，就需要读取并丢弃前面的字节
			_, err := io.CopyN(io.Discard, r, int64(start))
			if err != nil {
				return nil, fmt.Errorf("failed to skip bytes: %v", err)
			}
		}
	}

	// 创建缓冲区只读取需要的字节
	buf := make([]byte, length)
	_, err := io.ReadFull(r, buf)
	if err != nil {
		return nil, fmt.Errorf("failed to read register: %v", err)
	}

	return buf, nil
}

func ReadRegisterSingleFrom(r io.Reader, register int) ([]byte, error) {
	return ReadRegisterFrom(r, register, 1)
}

// ReadRegister
// Deprecated, 请使用 ReadRegisterFrom
func ReadRegister(b []byte, register, quantity int) []byte {
	start := register * 2
	if quantity == 0 {
		quantity = 1
	}
	end := start + quantity*2
	return b[start:end]
}

// ReadRegisterSingle
// Deprecated, 请使用 ReadRegisterSingleFrom
func ReadRegisterSingle(b []byte, register int) []byte {
	return ReadRegister(b, register, 1)
}

// ReadRegisterBit
// Deprecated, 请使用 ReadRegisterFrom
func ReadRegisterBit(b []byte, register int, splitter gnet.BitSplitter) gnet.BitSplit {
	return splitter.BitSplit(ReadRegister(b, register, 1))
}
