package viewdb

import (
	"github.com/tangs-drm/go-tool/util"
	"gopkg.in/mgo.v2/bson"
	"github.com/tangs-drm/go-tool/log"
	"github.com/tangs-drm/go-tool/dbm"
	"fmt"
)

func Record_Mongo(article_id int, ip string) error {
	info, err := C(VIEW_TIMES).Upsert(bson.M{
		"article": article_id,
		"ip": ip,
	}, bson.M{
		"$setOnInsert": bson.M{
			"_id": bson.NewObjectId().Hex(),
			"time": util.Now(),
			"attrs": util.Map{},
		},
		"$set": bson.M{
			"lastTime": util.Now(),
		},
		"$inc": bson.M{
			"count": 1,
		},
	})
	if err != nil {
		log.Error("[Record] record with id(%v), time(%v) error ->(%v)", article_id, util.Now(), err)
		return err
	}

	log.Debug("[Record] record with id(%v), time(%v) success with info(%v)", article_id, util.Now(), util.S2Json(info))
	return nil
}

// FindArticleId 根据文章名字查出文章的id
func FindArticleId(name string) (util.Map, error) {
	var sqlString = fmt.Sprintf("SELECT ID FROM POSTS WHERE SLUG = '%v'", name)
	rows, err := dbm.D().Query(sqlString)
	if err != nil {
		log.Error("[FindArticleId] find article id with name(%v) error ->(%v)", name, err)
		return nil, err
	}
	if !rows.Next() {
		log.Error("[FindArticleId] find article id with name(%v) not found", name)
		return util.Map{}, util.Error("name is not found")
	}
	var id int
	err = rows.Scan(&id)
	if err != nil {
		log.Error("[FindArticleId] find article id with name(%v) scan id error ->(%v)", name, err)
		return nil, err
	}
	var result = util.Map{
		"id": id,
	}
	return result, nil
}

// Record 根据文章id加浏览加1
func Record(article_id int) error {
	var err error

	var sqlString = "UPDATE PAGE_VIEW SET LAST_VIEW = ? AND TIMES = TIMES + 1 WHERE POST_ID = ?;"
	_, err = dbm.D().Exec(sqlString, util.Now10(), article_id)
	if err != nil {
		log.Error("[Record] exec record with article id (%v) with sqlString(%v) error ->(%v)", article_id, sqlString, err)
		return err
	}
	log.Debug("[Record] exec record with article id(%v) success", article_id)
	return nil
}