package models

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

type News struct {
	Model

	Title      string `gorm:"size:255;not null;" json:"title"`
	Content    string `gorm:"not null;" json:"content"`
	Top        uint8  `gorm:"not null;default:0" json:"top"`
	Highlight  uint8  `gorm:"not null;default:0" json:"highlight"`
	Status     uint8  `gorm:"not null;default:0" json:"status"`
	PlatformId int    `gorm:"not null;default:1" json:"platform_id"`
}

func (w News) TableName() string {
	return setting.DatabaseSetting.Name_Coin + ".article"
}

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

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

	return false, nil
}

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

	return count, nil
}

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

	return news, nil
}

func GetOneNews(maps interface{}) (*News, error) {
	var news News
	err := db.Where(maps).First(&news).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

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

	return &news, nil
}

func AddNews(data map[string]interface{}) (error) {
	news := News{
		Title:      data["title"].(string),
		Content:    data["content"].(string),
		Top:        data["top"].(uint8),
		Highlight:  data["highlight"].(uint8),
		Status:     data["status"].(uint8),
		PlatformId: data["platform_id"].(int),
	}
	if err := db.Create(&news).Error; err != nil {
		return err
	}

	return nil
}

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

	return nil
}

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

	return nil
}
