package viewapi

import (
	"net/http"
	"github.com/tangs-drm/go-tool/log"
	"github.com/tangs-drm/go-tool/util"
	thttp "github.com/tangs-drm/go-tool/http"
	"view/viewdb"
	"response"
)

func ViewRecord(w http.ResponseWriter, r *http.Request) {
	var code int
	var message string
	var err error
	var result util.Map
	defer func() {
		message = response.Message[code]
		thttp.WriteResponse(w, code, message, err, result)
	}()

	name := r.FormValue("name")
	if len(name) < 1 {
		code = 1
		err = util.Error("invalid name")
		log.Error("[ViewRecord] get form value:name error ->(%v)", err)
		return
	}

	log.Debug("ip info %v", r.RemoteAddr)

	info, err := viewdb.FindArticleId(name)
	if err != nil {
		code = 2
		log.Error("[ViewRecord] Find article id by name(%v) error ->(%v)", name, err)
		return
	}

	var aid int = info.Int("id")
	err = viewdb.Record_Mongo(info.Int("id"), r.RemoteAddr)
	if err != nil {
		code = 2
		log.Error("[ViewRecord] record with id(%v) error =>(%v)", aid, err)
		return
	}

	log.Debug("[ViewRecord] record with id(%v) success", aid)
	return
}
