package models

import (
	"encoding/json"
	"strconv"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type UserLog struct {
	Id      int
	Name    string `orm:"index"`
	Time    int64
	Operate string
	Data    string `orm:type(text)`
}

func init() {
	orm.RegisterModel(new(UserLog))
}

func (c *UserLog) TableName() string {
	return "tb_log"
}

func SaveLog(name string, operate string, v interface{}) (int64, error) {
	buff, _ := json.Marshal(v)
	l := &UserLog{
		Name:    name,
		Operate: operate,
		Time:    time.Now().Unix(),
		Data:    string(buff),
	}

	o := orm.NewOrm()
	return o.Insert(l)
}

func QueryLog(name string, begin_ts int64, end_ts int64, operate string, count int) []*UserLog {
	var logs []*UserLog

	sql := "SELECT * from tb_log"
	where := ""
	if name != "" {
		if where == "" {
			where = " name = '" + name + "'"
		} else {
			where += " and name = '" + name + "'"
		}
	}

	if begin_ts != 0 {
		if where == "" {
			where = " time >= " + strconv.Itoa(int(begin_ts))
		} else {
			where += " and time >= " + strconv.Itoa(int(begin_ts))
		}
	}

	if end_ts != 0 {
		if where == "" {
			where = " time <= " + strconv.Itoa(int(end_ts))
		} else {
			where += " and time <= " + strconv.Itoa(int(end_ts))
		}
	}

	if operate != "" {
		if where == "" {
			where = " operate = '" + operate + "'"
		} else {
			where += " and operate = '" + operate + "'"
		}
	}

	if where != "" {
		sql += " where " + where
	}

	sql += " order by time desc"

	if count > 0 {
		sql += " limit " + strconv.Itoa(count)
	}

	o := orm.NewOrm()
	_, err := o.Raw(sql).QueryRows(&logs)
	if err != nil {
		beego.Info(sql)

		beego.Warn("query log error, info: ", err.Error())
	}

	return logs
}
