package main

import (
	"net/http"
	"time"

	"github.com/labstack/echo/v4"
	"github.com/labstack/gommon/log"
)

func helloWorld(c echo.Context) error {
	return c.JSON(http.StatusOK, "Hello world!")
}

func getOpened(c echo.Context) error {
	mut.Lock()
	o := opened
	mut.Unlock()

	return c.JSON(http.StatusOK, o)
}

func setOpened(c echo.Context) error {
	var data ChangeOpenReq
	err := c.Bind(&data)
	if err != nil {
		return c.NoContent(http.StatusBadRequest)
	}

	if data.Opened == opened {
		return c.NoContent(http.StatusOK)
	}

	mut.Lock()
	opened = data.Opened
	if locked && alerts {
		var action string
		if opened {
			action = "opened"
		} else {
			action = "closed"
		}

		go sendAlert(action)
	}

	mut.Unlock()
	return c.NoContent(http.StatusOK)
}

func getLocked(c echo.Context) error {
	mut.Lock()
	l := locked
	mut.Unlock()

	return c.JSON(http.StatusOK, l)
}

func setLocked(c echo.Context) error {
	var data ChangeLockReq
	err := c.Bind(&data)
	if err != nil {
		return err
	}

	if data.Locked == locked {
		return c.NoContent(http.StatusOK)
	}

	mut.Lock()
	locked = data.Locked
	mut.Unlock()

	return c.NoContent(http.StatusOK)
}

func getAlerts(c echo.Context) error {
	mut.Lock()
	a := alerts
	mut.Unlock()

	return c.JSON(http.StatusOK, a)
}

func setAlerts(c echo.Context) error {
	var data ChangeAlertReq
	err := c.Bind(&data)
	if err != nil {
		return err
	}

	if data.For > 0 {
		log.Infof("pausing alerts for %d seconds", data.For)
		go func() {
			time.Sleep(time.Duration(data.For) * time.Second)

			mut.Lock()
			alerts = !data.Alerts
			mut.Unlock()
		}()
	}

	mut.Lock()
	alerts = data.Alerts
	mut.Unlock()

	return c.NoContent(http.StatusOK)
}
