package controllers

import (
	"github.com/kataras/iris/v12"
	"sparrow/pkg/models"
	"sparrow/services/knowoapi/services"
)

// OtaController api
type OtaController struct {
	Ctx     iris.Context
	Service services.OtaService
	Token   Token
}

// Post post
// POST /ota
func (a *OtaController) Post() {
	ptl := new(models.Ota)
	if err := parseBody(a.Ctx, ptl); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	ptl.VendorId = a.Token.getVendorID(a.Ctx)
	err := a.Service.Create(ptl)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, ptl)
}

// Delete delete
// DELETE /user/ota
func (a *OtaController) Delete() {
	Ota := new(models.Ota)
	if err := parseBody(a.Ctx, Ota); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	if err := a.Service.Delete(Ota); err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, "删除成功")
}

// Put 更新
// PUT /user/ota
func (a *OtaController) Put() {
	params := new(models.Ota)
	if err := parseBody(a.Ctx, params); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	if err := a.Service.Update(params); err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, "已保存")
}

// Get  Ota
// GET /user/ota?pi=&ps=&name=&version
func (a *OtaController) 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
	}
	name := a.Ctx.URLParam("name")
	version := a.Ctx.URLParam("version")
	vendorId := a.Token.getVendorID(a.Ctx)
	datas, total, err := a.Service.Query(pi, ps, name, vendorId, version)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}

	done(a.Ctx, map[string]interface{}{
		"list":  datas,
		"total": total,
	})
}

// PostUpgrade  Ota
// Post /ota/upgrade
func (a *OtaController) PostUpgrade() {
	params := new(models.OtaUpgradeParams)
	if err := parseBody(a.Ctx, params); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	params.VendorId = a.Token.getVendorID(a.Ctx)
	err := a.Service.Upgrade(*params)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, "下发成功")
}
