package events

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"os"
	"strings"
	"time"
	"sort"

	"box-gm/utils"
	// "log"
)

type RecordClient struct {
	EventTime   int64
	ServerId	string
	Scene		string
	EventId		string
	Label		string
}

type ClientRecordList []*RecordClient

func (a ClientRecordList) Len() int      { return len(a) }
func (a ClientRecordList) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ClientRecordList) Less(i, j int) bool {
	return a[i].EventTime > a[j].EventTime
}
func (a ClientRecordList) Sort() { sort.Sort(a) }

func Client_get_records(scene, eid string, startTime, endTime int) []*RecordClient {
	// 日期列表
	var dateList []string
	times := 0
	for {
		ti := startTime + times*86400
		if ti >= endTime {
			break
		}
		date := time.Unix(int64(ti), 0).Format("2006-01-02")
		dateList = append(dateList, date)
		times++
	}
	// log.Printf("ChatQuery_get_records dateList[%v]", dateList)
	var records ClientRecordList
	loc, _ := time.LoadLocation("Local")
	for _, date := range dateList {
		eventFile := fmt.Sprintf("%s/client-%s.log", utils.GetKeyConf("events", "path"), date)
		f, err := os.Open(eventFile)
		if err != nil {
			log.Printf("eventFile[%s] err[%v]", eventFile, err)
			continue
		}
		defer f.Close()
		buff := bufio.NewReader(f)
		for {
			line, err := buff.ReadString('\n')

			if err != nil || io.EOF == err {
				break
			}
			line = strings.TrimSpace(line)
			/* string.format(
			   "%s;%s;%s;%s;%s;%s;%s",
			   get_time_string(),
			   get_server_id(),
			   _tostring(uid),
			   _tostring(toUid),
			   _tostring(msgty),
			   _tostring(iCType),
			   _tostring(cnt)*/
			arr := strings.Split(line, ";")
			theTime, errTime := time.ParseInLocation("2006-01-02 15:04:05", arr[0], loc)
			if errTime == nil {
				ti := int(theTime.Unix())
				if ti >= startTime && ti <= endTime {
					// 场景
					if scene == "" || scene == arr[2] {
						// 事件id
						if eid == "" || eid == arr[3] {
							item := &RecordClient{}
							item.EventTime = utils.GetTime64(arr[0])
							item.ServerId = arr[1]
							item.Scene = arr[2]
							item.EventId = arr[3]
							item.Label = arr[4]

							records = append(records, item)
						}
					}
				}
			}
		}
	}
	records.Sort()

	// log.Printf("ChatQuery_get_records records[%v]", records)
	return records
}
