package models

import (
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/timeutil"
	"xorm.io/xorm"
)

type SearchRecord struct {
	ID int64 `xorm:"pk autoincr"`
	//user
	Keyword string `xorm:"NOT NULL"`
	//
	CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
}

func SaveSearchKeywordToDb(keyword string) error {
	record := &SearchRecord{
		Keyword: keyword,
	}
	sess := x.NewSession()
	defer sess.Close()
	_, err := sess.Insert(record)
	if err != nil {
		log.Info("insert error." + err.Error())
		return err
	}
	return nil
}

func setIssueQueryCondition(sess *xorm.Session, Keyword string, isPull bool, userId int64) {
	sess.And("issue.poster_id=?", userId)
	sess.And("issue.is_pull=?", isPull)
	sess.And("(issue.name like '%" + Keyword + "%' or issue.content like '%" + Keyword + "%')")
	sess.Join("INNER", "repository", "issue.repo_id = repository.id").And("repository.is_private = ?", true)
}

func SearchPrivateIssueOrPr(Page int, PageSize int, Keyword string, isPull bool, userId int64) ([]*Issue, int64, error) {
	sess := x.NewSession()
	defer sess.Close()
	setIssueQueryCondition(sess, Keyword, isPull, userId)
	count, err := sess.Count(new(Issue))
	if err != nil {
		return nil, 0, err
	}

	setIssueQueryCondition(sess, Keyword, isPull, userId)
	sess.Desc("issue.created_unix")
	sess.Limit(PageSize, (Page-1)*PageSize)
	issues := make([]*Issue, 0)
	if err := sess.Find(&issues); err != nil {
		return nil, 0, err
	} else {
		return issues, count, nil
	}
}

func setDataSetQueryCondition(sess *xorm.Session, Keyword string, userId int64) {
	sess.And("dataset.user_id=?", userId)
	sess.And("(dataset.title like '%" + Keyword + "%' or dataset.description like '%" + Keyword + "%')")
	sess.Join("INNER", "repository", "dataset.repo_id = repository.id").And("repository.is_private = ?", true)
}

func SearchDatasetBySQL(Page int, PageSize int, Keyword string, userId int64) ([]*Dataset, int64, error) {
	sess := x.NewSession()
	defer sess.Close()
	setDataSetQueryCondition(sess, Keyword, userId)
	count, err := sess.Count(new(Dataset))
	if err != nil {
		return nil, 0, err
	}

	setDataSetQueryCondition(sess, Keyword, userId)
	sess.Desc("dataset.created_unix")
	sess.Limit(PageSize, (Page-1)*PageSize)
	datasets := make([]*Dataset, 0)
	if err := sess.Find(&datasets); err != nil {
		return nil, 0, err
	} else {
		return datasets, count, nil
	}

}
