package models

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

type LiveCategory struct {
	Model

	Name       string `gorm:"not null;default:''" json:"name"`
	Logo       string `gorm:"not null;default:''" json:"logo"`
	Sort       uint8  `gorm:"not null;default:0" json:"sort"`
	PlatformId int64  `gorm:"not null;default:0" json:"platform_id"`
}

func (w LiveCategory) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".wallet_live_category"
}

func GetOneLiveCategory(id int) (*LiveCategory, error) {
	var category LiveCategory
	err := db.Where("id = ?", id).First(&category).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

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

	return &category, nil
}

func ExistLiveCategoryById(id int) (bool, error) {
	var category LiveCategory
	err := db.Select("id").Where("id = ?", id).First(&category).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}

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

	return false, nil
}

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

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

	return count, nil
}

func GetLiveCategory(pageNum, pageSize int, maps interface{}) ([]*LiveCategory, error) {
	var category []*LiveCategory

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

	return category, nil
}

func AddLiveCategory(data map[string]interface{}) (error) {
	category := LiveCategory{
		Name:       data["name"].(string),
		Sort:       data["sort"].(uint8),
		Logo:       data["logo"].(string),
		PlatformId: data["platform_id"].(int64),
	}
	if err := db.Create(&category).Error; err != nil {
		return err
	}

	return nil
}

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

	return nil
}

func DeleteLiveCategory(id int) error {
	if err := db.Where("id = ?", id).Delete(LiveCategory{}).Error; err != nil {
		return err
	}

	return nil
}
