package news_service

import (
	"bwallet/models"
	"time"
)

type News struct {
	Id         int
	Title      string
	Content    string
	Top        uint8
	Highlight  uint8
	PlatformId int
	SearchType int

	PageNum  int
	PageSize int
}

func (n *News) Get() (*models.News, error) {

	news, err := models.GetOneNews(n.getMaps())
	if err != nil {
		return nil, err
	}

	return news, nil
}

func (n *News) GetAll() ([]*models.News, error) {
	var news []*models.News

	news, err := models.GetNews(n.PageNum, n.PageSize, n.getMaps())
	if err != nil {
		return nil, err
	}

	return news, nil
}

func (n *News) Add() error {
	news := map[string]interface{}{
		"title":       n.Title,
		"content":     n.Content,
		"top":         n.Top,
		"highlight":   n.Highlight,
		"platform_id": n.PlatformId,
		"create_time": time.Now().UTC().Unix(),
	}

	if err := models.AddNews(news); err != nil {
		return err
	}

	return nil
}

func (n *News) Edit() error {
	return models.EditNews(n.Id, map[string]interface{}{
		"title":       n.Title,
		"content":     n.Content,
		"top":         n.Top,
		"highlight":   n.Highlight,
		"platform_id": n.PlatformId,
	})
}

func (n *News) ExistById() (bool, error) {
	return models.ExistNewsById(n.Id)
}

func (n *News) Count() (int, error) {
	return models.GetNewsTotal(n.getMaps())
}

func (n *News) Delete() error {
	return models.DeleteNews(n.Id)
}

func (n *News) getMaps() (map[string]interface{}) {
	maps := make(map[string]interface{})

	if n.Id != 0 {
		maps["id"] = n.Id
	}

	if n.Title != "" {
		maps["title"] = n.Title
	}

	if n.PlatformId != 0 {
		maps["platform_id"] = n.PlatformId
	}

	if n.SearchType != 0 {
		platform_id := [] int{n.PlatformId, n.SearchType}
		maps["search_type"] = platform_id
	}

	return maps
}
