package main

import (
	"gobot.io/x/gobot"
	"gobot.io/x/gobot/drivers/i2c"
	"sync"
)

type ADS7830 struct {
	//*gobot.Driver
	name       string
	connector  i2c.Connector
	connection i2c.Connection
	i2c.Config
	mutex sync.Mutex
}

func NewADS7830(c i2c.Connector, options ...func(config i2c.Config)) *ADS7830 {
	adc := &ADS7830{
		name:      gobot.DefaultName("ADS7830"),
		mutex:     sync.Mutex{},
		connector: c,
		Config:    i2c.NewConfig(),
	}

	for _, option := range options {
		option(adc)
	}

	return adc
}

func (adc *ADS7830) AnalogRead(channel int) (int, error) {
	adc.mutex.Lock()
	defer adc.mutex.Unlock()

	register := 0x84 | (((channel<<2 | channel>>1) & 0x07) << 4)
	value, err := adc.connection.ReadByteData(uint8(register))
	if err != nil {
		return 0, err
	}
	return int(value), nil
}

func (adc *ADS7830) Name() string {
	return adc.name
}

func (adc *ADS7830) SetName(name string) {
	adc.name = name
}

func (adc *ADS7830) Start() (err error) {
	bus := adc.GetBusOrDefault(adc.connector.GetDefaultBus())
	address := adc.GetAddressOrDefault(0x48)

	adc.connection, err = adc.connector.GetConnection(address, bus)
	if err != nil {
		return err
	}

	return nil
}

func (adc *ADS7830) Halt() error {
	return nil
}

func (adc *ADS7830) Connection() gobot.Connection {
	return adc.connector.(gobot.Connection)
}