package models

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

type Streamer struct {
	Uid           int32  `gorm:"type:int(11);primary key"`
	UserName      string `gorm:"type:varchar(64);unique;not null"`
	NickName      string `gorm:"type:varchar(128)"`
	Password      string `gorm:"type:varchar(32);not null"`
	RegTime       int64  `gorm:"type:datetime"`
	LastLoginTime int64  `gorm:"type:datetime"`
	RegIp         uint32 `gorm:"type:int(10)"`
	LastLoginIp   uint32 `gorm:"type:int(10)"`
	Status        uint8  `gorm:"not null;default:0"`
	PlatformId    int64  `gorm:"not null;default:0"`
}

func (w Streamer) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".wallet_streamer"
}

func GetStreamer(id int32) (*Streamer, error) {
	var live Streamer
	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 ExistStreamerById(id int32) (bool, error) {
	var live Streamer
	err := db.Select("uid").Where("uid = ?", id).First(&live).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}

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

	return false, nil
}

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

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

	return count, nil
}

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

	err := db.Where(maps).Preload("Category").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 AddStreamer(data map[string]interface{}) (error) {
	streamer := Streamer{
		UserName:      data["username"].(string),
		NickName:      data["nickname"].(string),
		Password:      data["password"].(string),
		RegTime:       time.Now().Unix(),
		LastLoginTime: time.Now().Unix(),
		RegIp:         data["reg_ip"].(uint32),
		LastLoginIp:   data["last_login_ip"].(uint32),
		Status:        data["status"].(uint8),
		PlatformId:    data["platform_id"].(int64),
	}

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

	return nil
}

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

	return nil
}

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

	return nil
}
