package main

import (
	"fmt"
	"net/http"
	"strconv"

	"gopkg.in/macaron.v1"
)

func jsonStatus(ctx *macaron.Context) {

	out := [][]string{}

	for num, o := range TheConfig.Outlets {
		pwr, _ := o.PowerStatus()
		pwrstr := "0"
		if pwr {
			pwrstr = "1"
		}
		out = append(out, []string{fmt.Sprintf("%d", num), o.Name, pwrstr})
	}

	ctx.JSON(http.StatusOK, Dictionary{
		"data": out,
	})
}

func jsonOutletPowerToggle(ctx *macaron.Context) {
	var outletnum64 uint64
	var err error

	outletnum64, err = strconv.ParseUint(ctx.Params(":outlet"), 10, 32)
	if err != nil {
		ctx.JSON(http.StatusOK, Dictionary{
			"data":  "error",
			"error": "No outlet specified",
		})
	}

	outletnum := uint(outletnum64)
	outlet, exists := TheConfig.Outlets[outletnum]
	if !exists {
		// error: outlet doesn't exists
		ctx.JSON(http.StatusOK, Dictionary{
			"data":  "error",
			"error": "Outlet doesn't exists",
		})
	}

	err = outlet.PowerToggle()
	if err != nil {
		ctx.JSON(http.StatusOK, Dictionary{
			"data":  "error",
			"error": "Can't toggle power",
		})
	}
	ctx.JSON(http.StatusOK, Dictionary{
		"data": "ok",
	})
}

func jsonOutletPowerON(ctx *macaron.Context) {
	var outletnum64 uint64
	var err error

	outletnum64, err = strconv.ParseUint(ctx.Params(":outlet"), 10, 32)
	if err != nil {
		ctx.JSON(http.StatusOK, Dictionary{
			"data":  "error",
			"error": "No outlet specified",
		})
	}
	outletnum := uint(outletnum64)

	outlet, exists := TheConfig.Outlets[outletnum]
	if !exists {
		// error: outlet doesn't exists
		ctx.JSON(http.StatusOK, Dictionary{
			"data":  "error",
			"error": "Outlet doesn't exists",
		})
	}

	err = outlet.PowerON()
	if err != nil {
		ctx.JSON(http.StatusOK, Dictionary{
			"data":  "error",
			"error": "Can't toggle power",
		})
	}
	ctx.JSON(http.StatusOK, Dictionary{
		"data": "ok",
	})
}

func jsonOutletPowerOFF(ctx *macaron.Context) {
	var outletnum64 uint64
	var err error

	outletnum64, err = strconv.ParseUint(ctx.Params(":outlet"), 10, 32)
	if err != nil {
		ctx.JSON(http.StatusOK, Dictionary{
			"data":  "error",
			"error": "No outlet specified",
		})
	}
	outletnum := uint(outletnum64)

	outlet, exists := TheConfig.Outlets[outletnum]
	if !exists {
		// error: outlet doesn't exists
		ctx.JSON(http.StatusOK, Dictionary{
			"data":  "error",
			"error": "Outlet doesn't exists",
		})
	}

	err = outlet.PowerOFF()
	if err != nil {
		ctx.JSON(http.StatusOK, Dictionary{
			"data":  "error",
			"error": "Can't toggle power",
		})
	}
	ctx.JSON(http.StatusOK, Dictionary{
		"data": "ok",
	})
}
