package services

import (
	"errors"
	"github.com/gogf/gf/util/guid"
	"sparrow/pkg/generator"
	"sparrow/pkg/models"
	"sparrow/services/knowoapi/model"
)

// ApplicationService 业务接口
type ApplicationService interface {
	Create(*models.Application) error
	Delete(*models.Application) error
	Update(*models.Application) (models.Application, error)
	// 查询App信息
	// 参数 ：厂商ID，APPKey
	GetAppInfo(string, string) (models.Application, error)
	GetVendorApps(vendorid string, pi, ps int, name string) ([]models.Application, int, error)
}

type appService struct {
	model  *model.All
	keyGen *generator.KeyGenerator
}

// NewAppService new app manager
func NewAppService(model *model.All, gen *generator.KeyGenerator) ApplicationService {
	return appService{
		model:  model,
		keyGen: gen,
	}
}

func (a appService) Create(app *models.Application) error {
	app.RecordId = guid.S()
	count, err := a.model.Application.GetAppCount(app.VendorID)
	if err != nil {
		return err
	}
	if count > 0 {
		return errors.New("一个厂商只能创建一个app")
	}
	err = a.model.Application.Create(app)
	if err != nil {
		return err
	}
	app.AppKey, _ = a.keyGen.GenRandomKey(app.RecordId)
	app.SecretKey, _ = generator.GenRandomPassword()

	return a.model.Application.Create(app)
}

func (a appService) Delete(app *models.Application) error {
	return a.model.Application.Delete(app)
}
func (a appService) Update(app *models.Application) (models.Application, error) {
	return a.model.Application.Update(app)
}
func (a appService) GetAppInfo(vendorid string, key string) (models.Application, error) {
	return a.model.Application.GetAppInfo(vendorid, key)
}

func (a appService) GetVendorApps(vendorid string, pi, ps int, name string) ([]models.Application, int, error) {
	return a.model.Application.GetVendorApps(vendorid, pi, ps, name)
}
