package main

import (
	"errors"
	"log"

	"periph.io/x/periph/conn/i2c"
	"periph.io/x/periph/conn/i2c/i2creg"
	"periph.io/x/periph/host"
)

// I2CBoard bla
type I2CBoard struct {
	i2cdev   i2c.Dev
	channels uint
	data     []byte
	inverted bool
}

// MyBoard bla
var MyBoard = I2CBoard{
	channels: 8,
	inverted: true,
}

func (b I2CBoard) channelStatus(ch uint) (bool, error) {
	if b.channels <= 0 {
		return false, errors.New("Board without channels")
	}
	if ch >= b.channels {
		return false, errors.New("Invalid channel")
	}
	write := []byte{0x0A}
	err := b.i2cdev.Tx(write, b.data)
	if err != nil {
		return false, err
	}
	byteToConsider := ch / b.channels
	value := (b.data[byteToConsider] >> (ch % 8) & 1) == 1
	if b.inverted {
		value = !value
	}
	return value, nil
}

func (b I2CBoard) channelToggle(ch uint) error {
	var mask byte

	if b.channels <= 0 {
		return errors.New("Board without channels")
	}
	if ch >= b.channels {
		return errors.New("Invalid channel")
	}

	//	if b.data == nil {
	_, _ = b.channelStatus(ch)
	//	}

	byteToConsider := ch / b.channels
	mask = 1 << (ch % 8)
	v := b.data[byteToConsider]
	v ^= mask
	b.data[byteToConsider] = v

	write := append([]byte{0x09}, b.data...)
	_, err := b.i2cdev.Write(write)
	if err != nil {
		return err
	}

	return nil
}

func init() {
	// Make sure periph is initialized.
	if _, err := host.Init(); err != nil {
		log.Fatal(err)
	}

	// Use i2creg I²C bus registry to find the first available I²C bus.
	mybus, err := i2creg.Open("/dev/i2c-0")
	if err != nil {
		log.Fatal(err)
	}
	//	defer mybus.Close()

	// bus 0
	// Dev is a valid conn.Conn.
	mydevice := &i2c.Dev{Addr: 0x27, Bus: mybus}

	// Send a command 0x10 and expect a 5 bytes reply.
	//	write := []byte{0x10}
	write := []byte{0x0}
	//	read := make([]byte, 5)
	//	if err := d.Tx(write, read); err != nil {
	if _, err := mydevice.Write(write); err != nil {
		log.Fatal(err)
	}

	MyBoard.i2cdev = *mydevice
	MyBoard.data = make([]byte, (MyBoard.channels-1)/8+1)

}
