package fan

// Code originally developed by sungo (https://sungo.io)
// Distributed under the terms of the 0BSD license https://opensource.org/licenses/0BSD

import (
	"github.com/d2r2/go-i2c"
	"github.com/d2r2/go-logger"
)

type Fan struct {
	conn *i2c.I2C
}

func init() {
	logger.ChangePackageLogLevel("i2c", logger.PanicLevel)
}

// From the argon python script:
// On an rpi4, the bus should be 1
// On any other rpi, the bus should 0
// On all platforms, the address should be 0x1a
func New(address uint8, bus int) (*Fan, error) {
	f := &Fan{}

	i, err := i2c.NewI2C(address, bus)
	f.conn = i

	return f, err
}

func (f *Fan) Bus() int {
	return f.conn.GetBus()
}

func (f *Fan) Addr() uint8 {
	return f.conn.GetAddr()
}

func (f *Fan) SafeClose() error {
	f.SetSpeed(50)
	return f.Close()
}

func (f *Fan) Close() error {
	return f.conn.Close()
}

func (f *Fan) SetSpeed(percent int) error {
	if percent > 100 {
		percent = 100
	} else if percent < 0 {
		percent = 0
	}

	_, err := f.conn.WriteBytes([]byte(string(percent)))
	return err
}
