package article_service

import (
	"bwallet/models"
	"time"
)

type Article struct {
	Id         int
	Title      string
	Source     string
	LogoPic    string
	ImgUrl     string
	Content    string
	Top        uint8
	Highlight  uint8
	PlatformId int
	SearchType int

	PageNum  int
	PageSize int
}

func (a *Article) Get() (*models.Article, error) {

	article, err := models.GetOneArticle(a.getMaps())
	if err != nil {
		return nil, err
	}

	return article, nil
}

func (a *Article) GetAll() ([]*models.Article, error) {
	var article []*models.Article

	article, err := models.GetArticle(a.PageNum, a.PageSize, a.getMaps())
	if err != nil {
		return nil, err
	}

	return article, nil
}

func (a *Article) Add() error {
	article := map[string]interface{}{
		"title":       a.Title,
		"source":      a.Source,
		"logo_pic":    a.LogoPic,
		"img_url":     a.ImgUrl,
		"content":     a.Content,
		"top":         a.Top,
		"highlight":   a.Highlight,
		"platform_id": a.PlatformId,
		"create_time": time.Now().UTC().Unix(),
	}

	if err := models.AddArticle(article); err != nil {
		return err
	}

	return nil
}

func (a *Article) Edit() error {
	return models.EditArticle(a.Id, map[string]interface{}{
		"title":       a.Title,
		"source":      a.Source,
		"logo_pic":    a.LogoPic,
		"img_url":     a.ImgUrl,
		"content":     a.Content,
		"top":         a.Top,
		"highlight":   a.Highlight,
		"platform_id": a.PlatformId,
	})
}

func (a *Article) ExistById() (bool, error) {
	return models.ExistArticleById(a.Id)
}

func (a *Article) Count() (int, error) {
	return models.GetArticleTotal(a.getMaps())
}

func (a *Article) Delete() error {
	return models.DeleteArticle(a.Id)
}

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

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

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

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

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

	return maps
}
