package models

import (
	"bwallet/pkg/setting"
	"github.com/jinzhu/gorm"
	"time"
)

type ClientApp struct {
	Model

	Type         uint8  `gorm:"not null;default:0" json:"type"`
	BundleId     string `gorm:"type:varchar(128)" json:"bundle_id,omitempty"`
	AppSignature string `gorm:"type:varchar(128)" json:"app_signature,omitempty"`
	AppPackage   string `gorm:"type:varchar(128)" json:"app_package,omitempty"`
	AppKey       string `gorm:"type:varchar(64)" json:"app_key,omitempty"`
	AppSecret    string `gorm:"type:varchar(128)" json:"app_secret,omitempty"`
	CreatedAt    int64  `gorm:"type:datetime" json:"created_at,omitempty"`
	Deadline     int64  `gorm:"type:datetime" json:"deadline,omitempty"`
}

func (a ClientApp) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".wallet_client_app"
}

func GetClientApp(id int32) (*ClientApp, error) {
	var app ClientApp
	err := db.Where("id = ?", id).First(&app).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	err = db.Model(&app).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return &app, nil
}

func ExistClientAppById(id int32) (bool, error) {
	var app ClientApp
	err := db.Select("id").Where("id = ?", id).First(&app).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}

	if app.ID > 0 {
		return true, nil
	}

	return false, nil
}

func GetClientAppTotal(maps interface{}) (int, error) {
	var count int

	if err := db.Model(&ClientApp{}).Where(maps).Count(&count).Error; err != nil {
		return 0, err
	}

	return count, nil
}

func GetClientApps(pageNum, pageSize int, maps interface{}) ([]*ClientApp, error) {
	var app []*ClientApp

	err := db.Where(maps).Order("created_at desc").Offset(pageNum).Limit(pageSize).Find(&app).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return app, nil
}

func AddClientApp(data map[string]interface{}) (error) {
	app := ClientApp{
		Type:         data["type"].(uint8),
		BundleId:     data["bundle_id"].(string),
		AppSignature: data["app_signature"].(string),
		AppPackage:   data["app_package"].(string),
		AppKey:       data["app_key"].(string),
		AppSecret:    data["app_secret"].(string),
		CreatedAt:    time.Now().Unix(),
		Deadline:     data["deadline"].(int64),
	}

	if err := db.Create(&app).Error; err != nil {
		return err
	}

	return nil
}

func EditClientApp(id int32, data interface{}) error {
	if err := db.Model(&ClientApp{}).Where("id = ?", id).Updates(data).Error; err != nil {
		return err
	}

	return nil
}

func DeleteClientApp(id int32) error {
	if err := db.Where("id = ?", id).Delete(ClientApp{}).Error; err != nil {
		return err
	}

	return nil
}
