package controllers

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

	"github.com/kataras/iris"
)

// AppController api
type AppController struct {
	Ctx     iris.Context
	Service services.ApplicationService
	Token   Token
}

// Post 创建app
// POST /application
func (a *AppController) Post() {
	app := new(models.Application)
	if err := parseBody(a.Ctx, app); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	app.VendorID = a.Token.getVendorID(a.Ctx)
	err := a.Service.Create(app)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, app)
}

// Get 获取我的app
// GET /application?pi=1&ps=&name=
func (a *AppController) 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")
	ds, total, err := a.Service.GetVendorApps(a.Token.getVendorID(a.Ctx), pi, ps, name)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, map[string]interface{}{
		"list":  ds,
		"total": total,
	})
}

// Delete 删除
// DELETE /application
func (a *AppController) Delete() {
	app := new(models.Application)
	if err := parseBody(a.Ctx, app); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	err := a.Service.Delete(app)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, "删除成功")
}

// GetBy 获取app信息
// GET /application/{key}
func (a *AppController) GetBy(key string) {
	app, err := a.Service.GetAppInfo(a.Token.getVendorID(a.Ctx), key)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, app)
}

// Put 更新
// PUT /application
func (a *AppController) Put() {
	app := new(models.Application)
	if err := parseBody(a.Ctx, app); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	result, err := a.Service.Update(app)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, result)
}
