package gpio

import (
	"io"
	"log"
	"time"

	gpio "github.com/stianeikeland/go-rpio/v4"
)

type gpioPin struct {
	logger *log.Logger
	pin    gpio.Pin
}

type Pin interface {
	Init() error
	PowerOn()
	PowerOff()
	io.Closer
}

func New(logger *log.Logger, pin uint8) Pin {
	return gpioPin{
		logger: logger,
		pin:    gpio.Pin(pin),
	}
}

func (p gpioPin) Init() error {
	return gpio.Open()
}

func (p gpioPin) sendOnOffSignal() {
	p.pin.Output()
	p.logger.Println("Power on 0/3 + 100ms")
	p.pin.Low()
	p.pin.Toggle()
	time.Sleep(100 * time.Millisecond)

	p.logger.Println("Power on 1/3 + 3s")
	p.pin.High()
	p.pin.Toggle()
	time.Sleep(3 * time.Second)

	p.logger.Println("Power on 2/3 + 30s")
	p.pin.Low()
	p.pin.Toggle()
	time.Sleep(30 * time.Second)

	p.logger.Println("Power on 3/3")
}

func (p gpioPin) PowerOn() {
	p.sendOnOffSignal()
}

func (p gpioPin) PowerOff() {
	p.sendOnOffSignal()
}

func (p gpioPin) Close() error {
	return gpio.Close()
}