package main

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

	"github.com/go-macaron/pongo2"
	"gopkg.in/macaron.v1"
)

func statusPage(ctx *macaron.Context) {
	ctx.Data["pluglist"] = []Dictionary{
		{"id": 1, "description": "p1"},
		{"id": 2, "description": "p2"},
		{"id": 3, "description": "p3"},
		{"id": 4, "description": "p4"},
		{"id": 5, "description": "p5"},
		{"id": 6, "description": "p6"},
		{"id": 7, "description": "p7"},
		{"id": 8, "description": "p8"},
	}
	ctx.HTML(200, "status") // 200 is the response code.
}

func jsonStatus(ctx *macaron.Context) {

	p0, err := MyBoard.channelStatus(0)
	if err != nil {
		log.Fatal(err)
	}

	p1, err := MyBoard.channelStatus(1)
	if err != nil {
		log.Fatal(err)
	}

	p2, err := MyBoard.channelStatus(2)
	if err != nil {
		log.Fatal(err)
	}

	p3, err := MyBoard.channelStatus(3)
	if err != nil {
		log.Fatal(err)
	}

	p4, err := MyBoard.channelStatus(4)
	if err != nil {
		log.Fatal(err)
	}

	p5, err := MyBoard.channelStatus(5)
	if err != nil {
		log.Fatal(err)
	}

	p6, err := MyBoard.channelStatus(6)
	if err != nil {
		log.Fatal(err)
	}

	p7, err := MyBoard.channelStatus(7)
	if err != nil {
		log.Fatal(err)
	}

	ctx.JSON(http.StatusOK, Dictionary{
		"data": [][]string{
			{"0", "p0", fmt.Sprint(p0)},
			{"1", "p1", fmt.Sprint(p1)},
			{"2", "p2", fmt.Sprint(p2)},
			{"3", "p3", fmt.Sprint(p3)},
			{"4", "p4", fmt.Sprint(p4)},
			{"5", "p5", fmt.Sprint(p5)},
			{"6", "p6", fmt.Sprint(p6)},
			{"7", "p7", fmt.Sprint(p7)},
		},
	})
}

func jsonOutletToggle(ctx *macaron.Context) {
	id, err := strconv.ParseUint(ctx.Params(":id"), 10, 64)
	if err != nil {
		log.Fatal(err)
	}
	err = MyBoard.channelToggle(uint(id))
	if err != nil {
		log.Fatal(err)
	}
	ctx.JSON(http.StatusOK, Dictionary{
		"data": "ok",
	})
}

func startServer() {
	m := macaron.Classic()
	m.Use(pongo2.Pongoer())
	m.Use(macaron.Static("static"))
	//	m.Get("/", myHandler)

	m.Get("/", statusPage)
	m.Get("/json/status", jsonStatus)
	m.Post("/json/outlet/:id/toggle", jsonOutletToggle)

	m.Get("/boards", func(ctx *macaron.Context) {
		ctx.HTML(200, "boards") // 200 is the response code.
	})

	log.Println("Server is running...")
	log.Println(http.ListenAndServe("0.0.0.0:4000", m))
}
