package models

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

type LiveInfo struct {
	Model

	Title      string `gorm:"not null;default:''" json:"title"`
	Cover      string `gorm:"not null;default:''" json:"cover"`
	CategoryId uint8  `gorm:"not null;default:0" json:"category_id"`
	Duration   uint32 `gorm:"not null;default:0" json:"duration"`
	Attendance uint32 `gorm:"not null;default:0" json:"attendance"`
	Mode       uint8  `gorm:"not null;default:1" json:"mode"`
	ApplyId    uint32 `gorm:"not null;default:0" json:"apply_id"`
	Status     uint8  `gorm:"not null;default:0" json:"status"`
	Sort       uint8  `gorm:"not null;default:0" json:"sort"`
}

func (w LiveInfo) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".wallet_live_info"
}

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

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

	return &live, nil
}

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

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

	return false, nil
}

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

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

	return count, nil
}

func GetLiveInfo(pageNum, pageSize int, maps interface{}) ([]*LiveInfo, error) {
	var live []*LiveInfo

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

	return live, nil
}

func AddLiveInfo(data map[string]interface{}) (error) {
	live := LiveInfo{
		Title:      data["title"].(string),
		Cover:      data["cover"].(string),
		CategoryId: data["category_id"].(uint8),
		Duration:   data["duration"].(uint32),
		Attendance: data["attendance"].(uint32),
		Mode:       data["mode"].(uint8),
		ApplyId:    data["apply_id"].(uint32),
		Status:     data["status"].(uint8),
		Sort:       data["sort"].(uint8),
	}
	if err := db.Create(&live).Error; err != nil {
		return err
	}

	return nil
}

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

	return nil
}

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

	return nil
}
