package client_app_service

import (
	"bwallet/models"
)

type ClientApp struct {
	Id           int32  `json:"omitempty"`
	Type         uint8  `json:"omitempty"`
	BundleId     string `json:"omitempty"`
	AppSignature string `json:"omitempty"`
	AppPackage   string `json:"omitempty"`
	AppKey       string `json:"omitempty"`
	AppSecret    string `json:"omitempty"`
	CreatedAt    int64
	Deadline     int64

	PageNum  int
	PageSize int
}

func (a *ClientApp) GetClientApp() (*models.ClientApp, error) {
	app, err := models.GetClientApp(a.Id)
	if err != nil {
		return nil, err
	}

	return app, nil
}

func (a *ClientApp) GetAll() ([]*models.ClientApp, error) {
	var app []*models.ClientApp

	app, err := models.GetClientApps(a.PageNum, a.PageSize, a.getMaps())
	if err != nil {
		return nil, err
	}

	return app, nil
}

func (a *ClientApp) Add() error {
	app := map[string]interface{}{
		"type":          a.Type,
		"bundle_id":     a.BundleId,
		"app_signature": a.AppSignature,
		"app_package":   a.AppPackage,
		"app_secret":    a.AppSecret,
		"deadline":      a.Deadline,
	}

	if err := models.AddClientApp(app); err != nil {
		return err
	}

	return nil
}

func (a *ClientApp) Edit() error {
	return models.EditClientApp(a.Id, map[string]interface{}{
		"type":          a.Type,
		"bundle_id":     a.BundleId,
		"app_signature": a.AppSignature,
		"app_package":   a.AppPackage,
		"app_secret":    a.AppSecret,
		"deadline":      a.Deadline,
	})
}

func (a *ClientApp) ExistById() (bool, error) {
	return models.ExistClientAppById(a.Id)
}

func (a *ClientApp) Count() (int, error) {
	return models.GetClientAppTotal(a.getMaps())
}

func (a *ClientApp) Delete() error {
	return models.DeleteClientApp(a.Id)
}

func (a *ClientApp) getMaps() (map[string]interface{}) {
	maps := make(map[string]interface{})

	if a.Id != 0 {
		maps["id"] = a.Id
	}

	if a.AppKey != "" {
		maps["app_key"] = a.AppKey
	}

	if a.AppSecret != "" {
		maps["app_secret"] = a.AppSecret
	}

	return maps
}
