package controllers

import (
	"sparrow/pkg/models"
	"sparrow/services/knowoapi/services"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
)

// AlertController api
type AlertController struct {
	Ctx     iris.Context
	Service services.AlertService
	Token   Token
}

// Post 添加告警规则
// POST /alert
func (a *AlertController) Post() {
	alert := new(models.AlarmRule)
	if err := parseBody(a.Ctx, alert); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	alert.VendorID = a.Token.getVendorID(a.Ctx)
	err := a.Service.Create(alert)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, alert)
}

// Delete 删除
// DELETE /alert
func (a *AlertController) Delete() {
	alert := new(models.AlarmRule)
	if err := parseBody(a.Ctx, alert); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	if alert.VendorID != a.Token.getVendorID(a.Ctx) {
		responseError(a.Ctx, ErrNormal, "没有权限")
		return
	}
	err := a.Service.Delete(alert)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, "删除失败"+err.Error())
		return
	}
	done(a.Ctx, "删除成功")
}

// Put 删除
// PUT /alert
func (a *AlertController) Put() {
	alert := new(models.AlarmRule)
	if err := parseBody(a.Ctx, alert); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	if alert.VendorID != a.Token.getVendorID(a.Ctx) {
		responseError(a.Ctx, ErrNormal, "没有权限")
		return
	}

	_alert, err := a.Service.Update(a.Token.getVendorID(a.Ctx), alert)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, _alert)
}

// GetBy 根据ID查询
// GET /alert/{id}
func (a *AlertController) GetBy(id string) {
	alert, err := a.Service.GetRule(a.Token.getVendorID(a.Ctx), id)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, alert)
}

// Get 获取告警列表
// GET /alert
func (a *AlertController) Get() {
	pi, err := a.Ctx.URLParamInt("pi")
	if err != nil {
		badRequest(a.Ctx, err)
		return
	}
	ps, err := a.Ctx.URLParamInt("ps")
	if err != nil {
		badRequest(a.Ctx, err)
		return
	}
	proid, err := a.Ctx.URLParamInt("proid")
	if err != nil {
		proid = 0
	}
	ptlid, err := a.Ctx.URLParamInt("ptlid")
	if err != nil {
		ptlid = 0
	}
	name := a.Ctx.URLParam("name")
	ds, total, err := a.Service.GetAlarmRules(a.Token.getVendorID(a.Ctx), pi, ps, proid, ptlid, name)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, map[string]interface{}{
		"list":  ds,
		"total": total,
	})

}

// BeforeActivation inside router
func (a *AlertController) BeforeActivation(b mvc.BeforeActivation) {
	b.Handle("GET", "/status/{alertid:int}/{status:int}", "SetStatus") //设置启用、禁用状态
}

// SetStatus set rule status
func (a *AlertController) SetStatus() {
	id := a.Ctx.Params().Get("alertid")
	status, _ := a.Ctx.Params().GetInt("status")
	alert, err := a.Service.SetRuleStatus(a.Token.getVendorID(a.Ctx), id, status)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, alert.Status)
}
