package main

import (
	"fmt"
	"net/http"

	jwt "github.com/dgrijalva/jwt-go"
	"github.com/dgrijalva/jwt-go/request"
	"github.com/go-martini/martini"
)

func ValidateTokenMiddleware(w http.ResponseWriter, r *http.Request, c martini.Context) {

	token, err := request.ParseFromRequest(r, request.AuthorizationHeaderExtractor,
		func(token *jwt.Token) (interface{}, error) {
			return []byte(SignedString), nil
		})
	if err == nil {
		if token.Valid {
			c.Next()
		} else {
			w.WriteHeader(http.StatusUnauthorized)
			fmt.Fprint(w, "Token is not valid")
		}
	} else {
		w.WriteHeader(http.StatusUnauthorized)
		fmt.Fprint(w, fmt.Sprintf("Unauthorized access to this resource:%s", err.Error()))
	}
}

// martini router
func route(m *martini.ClassicMartini) {
	m.Group("/application/v1", func(r martini.Router) {
		// find a device by key
		r.Get("/device/info", GetDeviceInfoByKey)

		// find a device by identifier
		r.Get("/devices/:identifier/info", ApplicationAuthOnDeviceIdentifer, GetDeviceInfoByIdentifier)

		// get devie current status
		r.Get("/devices/:identifier/status/current",
			ApplicationAuthOnDeviceIdentifer, CheckDeviceOnline, CheckProductConfig,
			GetDeviceCurrentStatus)

		// get devie latest status
		r.Get("/devices/:identifier/status/latest",
			ApplicationAuthOnDeviceIdentifer, CheckDeviceOnline, CheckProductConfig,
			GetDeviceLatestStatus)

		// set device status
		r.Put("/devices/:identifier/status",
			ApplicationAuthOnDeviceIdentifer, CheckDeviceOnline, CheckProductConfig,
			SetDeviceStatus)

		// send a command to device
		r.Post("/devices/:identifier/commands",
			ApplicationAuthOnDeviceIdentifer, CheckDeviceOnline, CheckProductConfig,
			SendCommandToDevice)

		// and a rule to device
		r.Post("/devices/:identifier/rules",
			ApplicationAuthOnDeviceIdentifer, CheckDeviceIdentifier,
			AddRule)
		r.Get("/devices/check_net_config", CheckDeviceNetConfig)

		r.Get("/devices/online", CheckDeviceIsOnline)
	}, ValidateTokenMiddleware)

	m.Post("/application/auth", AppAuth)

}
