package routers

import (
	"github.com/gin-gonic/gin"
	_ "chain33-pai/docs"
	"chain33-pai/routers/api/v1"
	"net/http"
)

// InitRouter initialize routing information
func InitRouter() *gin.Engine {
	  r  := gin.New()
	  r.Use(gin.Logger())
	  r.Use(gin.Recovery())
		r.Use(Cors())
	apiv1 := r.Group("/pai")
	//获取树莓派基本信息
	apiv1.POST("/devdetail",v1.GetDevdetail)
	//获取树莓派基本信息
	apiv1.POST("/resetwallet",v1.ResetWallet)
	//更新bityuan节点 下载替换 重启
	apiv1.POST("/updatenode",v1.UpdateNodeNew)
	//检查节点是否还在更新同步 节点6.4.0大版本更新可能需要十几个小时 故加此接口
	apiv1.POST("/nodeupdate",v1.UpdateNodeStatus)
	apiv1.POST("/devstatus",v1.GetDevstatus)
	apiv1.POST("/updatedetail",v1.UpdateDetail)
	apiv1.POST("/version",v1.Version)
	apiv1.POST("/reset",v1.ResetNode)
	apiv1.POST("/nodeinfo",v1.NodeInfo)

	//本程序版本
	apiv1.POST("/paiversion",v1.GetPaiVersion)
	//本程序下载新版本
	apiv1.POST("/updatepai",v1.UpdatePaiNew)
	//获取下载进度
	apiv1.POST("/dpercent",v1.GetDPercent)
	//获取外网ip
	apiv1.POST("/external",v1.GetExternal)
	//服务器状态
	apiv1.POST("/serverstatus",v1.GetServerStatus)
	//反馈信息
	apiv1.POST("/feedback",v1.FeedBackWithoutSSH)
	//反馈处理进度
	apiv1.POST("/iscomplete",v1.FeedBackStatusWithoutSSH)
	//反馈信息
	apiv1.POST("/feedback1",v1.FeedBack)
	//反馈处理进度
	apiv1.POST("/iscomplete1",v1.FeedBackStatus)
	apiv1.POST("/escrowpassword",v1.EscrowPasswd)
	//pai更新完成用户手动重启设备
	//apiv1.POST("/isreboot",v1.IsReBoot)
	//重启节点
	apiv1.POST("/restartnode",v1.RestartNode)
	//安全关闭节点，不会再重启  除非是重启树莓派
	apiv1.POST("/closenode",v1.CloseNode)
	//sudo poweroff
	apiv1.POST("/poweroff",v1.PoweroffPai)
	//test
	apiv1.POST("/test",v1.Test)
	apiv1.POST("/rollback",v1.Rollback)
	return r
}

// 处理跨域请求,支持options访问
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token,Authorization") //Content-Type,AccessToken,X-CSRF-Token,Authorization,Token,FZM-APP-ID
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")

		// 放行所有OPTIONS方法，因为有的模板是要请求两次的
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}

		// 处理请求
		c.Next()
	}
}
