package controllers

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"

	"git.kingpenguin.tk/chteufleur/datahouse.git/models/relay"
	"git.kingpenguin.tk/chteufleur/datahouse.git/models/variables"
	"strings"
	"time"
)

/*
--------------------------------------------------------------------------------
*/

type ViewRelayController struct {
	beego.Controller
}

func (c *ViewRelayController) Prepare() {
	sess := c.GetSession(variables.SessionName)
	if sess == nil {
		c.Redirect(variables.LoginRouteNoRegex+variables.ViewRelaysRoute, 302)
	} else {
		c.Data["IsAuthentificated"] = true
	}

	c.Data["IsViewRelay"] = true
	c.Data["version"] = variables.Version
}

func (c *ViewRelayController) Get() {
	c.Data["relays"] = relay.GetAllRelay()

	mac := c.Ctx.Input.Param(":sensor")
	r := relay.GetRelayByMac(mac)
	if r.Id != 0 {
		c.Data["isRelaySelected"] = true
		c.Data["relayMac"] = r.Mac
		if r.Description != "" {
			c.Data["relayDescription"] = r.Description
		} else {
			c.Data["relayDescription"] = r.Mac
		}
	}

	c.TplNames = "relay.tpl"
}

func (c *ViewRelayController) Post() {
	mac := c.Ctx.Input.Param(":sensor")
	r := relay.GetRelayByMac(mac)
	ret := ""
	if r.Id != 0 {
		ret += r.Mac + "/"
		if r.IpAddress != "" {
			getRep, err := httplib.Get("http://"+r.IpAddress+"/status").SetTimeout(3*time.Second, 3*time.Second).String()
			if err == nil {
				ret += getRep
			} else {
				relay.UpdateSensorIpAddress(r.Mac, "")
			}
		}
	}
	c.Ctx.Output.Body([]byte(ret))
}

/*
--------------------------------------------------------------------------------
*/

type AddRelayController struct {
	beego.Controller
}

func (c *AddRelayController) Get() {
	ip := strings.Split(c.Ctx.Request.RemoteAddr, ":")[0]
	mac := c.Ctx.Input.Param(":sensor")
	relay.UpdateSensorIpAddress(mac, ip)

	c.Ctx.Output.Body([]byte("OK"))
}

/*
--------------------------------------------------------------------------------
*/

type CommandRelayController struct {
	beego.Controller
}

func (c *CommandRelayController) Prepare() {
	sess := c.GetSession(variables.SessionName)
	if sess == nil {
		c.Redirect(variables.LoginRouteNoRegex+variables.CommandRelayRoute, 302)
	}
}

func (c *CommandRelayController) Post() {
	mac := c.Ctx.Input.Param(":sensor")
	r := relay.GetRelayByMac(mac)
	if r.Id != 0 {
		httplib.Get("http://"+r.IpAddress+"/toggle").SetTimeout(3*time.Second, 3*time.Second).String()
	}

	c.Ctx.Output.Body([]byte(""))
}
