package models

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

type LiveBanner struct {
	Model

	TargetLink string `json:"target_link"`
	ImageUrl   string `json:"image_url"`
	Title      string `json:"title"`
	PlatformId int    `json:"platform_id"`
	Sort       int32  `json:"sort"`
	Status     uint8  `json:"status"`
}

func (b LiveBanner) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".wallet_live_banner"
}

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

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

	return false, nil
}

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

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

	return &banner, nil
}

func GetLiveBannerTotal(maps interface{}) (int, error) {
	var count int
	if err := db.Model(&LiveBanner{}).Where(maps).Count(&count).Error; err != nil {
		return 0, err
	}

	return count, nil
}

func GetLiveBanners(pageNum, pageSize int, maps interface{}) ([]*LiveBanner, error) {
	var banners []*LiveBanner
	err := db.Where(maps).Offset(pageNum).Limit(pageSize).Find(&banners).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return banners, nil
}

func AddLiveBanner(data map[string]interface{}) (error) {
	banner := LiveBanner{
		TargetLink: data["target_link"].(string),
		ImageUrl:   data["image_url"].(string),
		Title:      data["title"].(string),
		PlatformId: data["platform_id"].(int),
		Sort:       data["sort"].(int32),
		Status:     data["status"].(uint8),
	}
	if err := db.Create(&banner).Error; err != nil {
		return err
	}

	return nil
}

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

	return nil
}

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

	return nil
}
