package admin

import (
	"gitote/gitote/models"
	"gitote/gitote/pkg/context"
	"gitote/gitote/pkg/setting"

	"github.com/Unknwon/com"
	"gitlab.com/yoginth/paginater"
	log "gopkg.in/clog.v1"
)

const (
	// NOTICES page template
	NOTICES = "admin/notice"
)

// Notices shows admin notices page
func Notices(c *context.Context) {
	c.Data["Title"] = "System Notices"
	c.Data["PageIsAdmin"] = true
	c.Data["PageIsAdminNotices"] = true

	total := models.CountNotices()
	page := c.QueryInt("page")
	if page <= 1 {
		page = 1
	}
	c.Data["Page"] = paginater.New(int(total), setting.UI.Admin.NoticePagingNum, page, 5)

	notices, err := models.Notices(page, setting.UI.Admin.NoticePagingNum)
	if err != nil {
		c.Handle(500, "Notices", err)
		return
	}
	c.Data["Notices"] = notices

	c.Data["Total"] = total
	c.HTML(200, NOTICES)
}

// DeleteNotices deletes notices
func DeleteNotices(c *context.Context) {
	strs := c.QueryStrings("ids[]")
	ids := make([]int64, 0, len(strs))
	for i := range strs {
		id := com.StrTo(strs[i]).MustInt64()
		if id > 0 {
			ids = append(ids, id)
		}
	}

	if err := models.DeleteNoticesByIDs(ids); err != nil {
		c.Flash.Error("DeleteNoticesByIDs: " + err.Error())
		c.Status(500)
	} else {
		c.Flash.Success("System notices have been deleted successfully.")
		c.Status(200)
	}
}

// EmptyNotices emty notices list
func EmptyNotices(c *context.Context) {
	if err := models.DeleteNotices(0, 0); err != nil {
		c.Handle(500, "DeleteNotices", err)
		return
	}

	log.Trace("System notices deleted by admin (%s): [start: %d]", c.User.Name, 0)
	c.Flash.Success("System notices have been deleted successfully.")
	c.Redirect(setting.AppSubURL + "/admin/notices")
}
