package service

import (
	"bbs-go/dao"
	"bbs-go/model"
	"bbs-go/model/constants"
	"bbs-go/util/simple"
)

var UserFeedService = newUserFeedService()

func newUserFeedService() *userFeedService {
	return &userFeedService{}
}

type userFeedService struct {
}

func (s *userFeedService) Get(id int64) *model.UserFeed {
	return dao.UserFeedDao.Get(simple.DB(), id)
}

func (s *userFeedService) Take(where ...interface{}) *model.UserFeed {
	return dao.UserFeedDao.Take(simple.DB(), where...)
}

func (s *userFeedService) Find(cnd *simple.SqlCnd) []model.UserFeed {
	return dao.UserFeedDao.Find(simple.DB(), cnd)
}

func (s *userFeedService) FindOne(cnd *simple.SqlCnd) *model.UserFeed {
	return dao.UserFeedDao.FindOne(simple.DB(), cnd)
}

func (s *userFeedService) FindPageByParams(params *simple.QueryParams) (list []model.UserFeed, paging *simple.Paging) {
	return dao.UserFeedDao.FindPageByParams(simple.DB(), params)
}

func (s *userFeedService) FindPageByCnd(cnd *simple.SqlCnd) (list []model.UserFeed, paging *simple.Paging) {
	return dao.UserFeedDao.FindPageByCnd(simple.DB(), cnd)
}

func (s *userFeedService) Count(cnd *simple.SqlCnd) int64 {
	return dao.UserFeedDao.Count(simple.DB(), cnd)
}

func (s *userFeedService) Create(t *model.UserFeed) error {
	return dao.UserFeedDao.Create(simple.DB(), t)
}

func (s *userFeedService) Update(t *model.UserFeed) error {
	return dao.UserFeedDao.Update(simple.DB(), t)
}

func (s *userFeedService) Updates(id int64, columns map[string]interface{}) error {
	return dao.UserFeedDao.Updates(simple.DB(), id, columns)
}

func (s *userFeedService) UpdateColumn(id int64, name string, value interface{}) error {
	return dao.UserFeedDao.UpdateColumn(simple.DB(), id, name, value)
}

func (s *userFeedService) Delete(id int64) {
	dao.UserFeedDao.Delete(simple.DB(), id)
}

func (s *userFeedService) DeleteByUser(userId, authorId int64) {
	simple.DB().Where("user_id = ? and author_id = ?", userId, authorId).Delete(model.UserFeed{})
}

func (s *userFeedService) DeleteByDataId(dataId int64, dataType string) {
	simple.DB().Where("data_id = ? and data_type = ?", dataId, dataType).Delete(model.UserFeed{})
}

func (s *userFeedService) GetTopics(userId int64, cursor int64) (topics []model.Topic, nextCursor int64, hasMore bool) {
	var limit = 20
	cnd := simple.NewSqlCnd().Eq("user_id", userId)
	cnd.Eq("data_type", constants.EntityTopic)
	if cursor > 0 {
		cnd.Lt("create_time", cursor)
	}
	cnd.Desc("create_time").Limit(limit)

	userFeeds := dao.UserFeedDao.Find(simple.DB(), cnd)
	if len(userFeeds) > 0 {
		nextCursor = userFeeds[len(userFeeds)-1].CreateTime
		hasMore = len(userFeeds) >= limit
	} else {
		nextCursor = cursor
	}

	var topicIds []int64
	for _, item := range userFeeds {
		topicIds = append(topicIds, item.DataId)
	}
	topics = TopicService.GetTopicByIds(topicIds)

	return
}
