package events

import (
	"fmt"
	"os"
	"bufio"
	"io"
	"strings"
	"math"

	"box-gm/utils"
	"time"
	// "log"
	"github.com/tealeg/xlsx"
	"github.com/astaxie/beego"
)

type RecordLogin struct {
	EventTime   string
	ServerId	string
	Uid         int
	RegisteTime	int64
	IP      	string
}
type RecordLoginArray []*RecordLogin

// 登录分布
func Login_get_day_time_count(date string, serverId string) (map[int]int, int) {
	var timeCount = make(map[int]int)
	var playerLevel = make(map[int]int)
	
	f, err := os.Open(fmt.Sprintf("%s/login-%s.log", utils.GetKeyConf("events", "path"), date))
	if err != nil {
		return timeCount, 0
	}
	defer f.Close()


	totalCount := 0
	startTime := utils.GetTime(date+" 00:00:00")
	
	buff := bufio.NewReader(f)
	for {
		line, err := buff.ReadString('\n')

		if err != nil || io.EOF == err {
			break
		}
		line = strings.TrimSpace(line)

		arr := strings.Split(line, ";")
		if serverId == "0" || arr[1] == serverId {
			eventTime := utils.GetTime(arr[0])
			uid := utils.StringToInt(arr[2])
			if playerLevel[uid] == 0 {
				totalCount ++
			}
			playerLevel[uid] = eventTime

			sec := eventTime - startTime
			sec = int(math.Floor(float64(sec/300)))
			timeCount[sec] ++
		}
	}

	return timeCount, totalCount
}

func Login_get_range_day_time_count(days int, serverId string) ([]*tgSeries, []string) {
	var series []*tgSeries
	currTime := int(time.Now().Unix())
	dayCount := 0
	for {
		tiEvent := currTime - 86400*dayCount
		date := time.Unix(int64(tiEvent), 0).Format("2006-01-02")
		item := &tgSeries{}
		glCount, totalCount := Login_get_day_time_count(date, serverId)
		item.Name = date + fmt.Sprintf(" 活跃人数:%d", totalCount)
		for i:=0; i < 289; i++ {
			item.Data = append(item.Data, glCount[i])
		}
		item.MapCount = glCount
		series = append(series, item)
		// log.Printf("login date[%s] item[%v]", date, item)

		dayCount ++
		if dayCount > days {
			break
		}
	}
	var arrCate []string
	loc, _ := time.LoadLocation("Local")
	theTime, _ := time.ParseInLocation("2006-01-02 15:04:05", time.Now().Format("2006-01-02") + " 00:00:00", loc)
	for i:=0; i < 289; i++ {
		ti := theTime.Add(time.Minute*5*time.Duration(i))
		arrCate = append(arrCate, fmt.Sprintf("%02d:%02d:%02d", ti.Hour(), ti.Minute(), ti.Second()))
	}
	return series, arrCate
}

// 保存文件
func Save_login_records(series []*tgSeries, user string) string {
	var file *xlsx.File
	var sheet *xlsx.Sheet
	var row *xlsx.Row
	var err error

	file = xlsx.NewFile()
	sheet, err = file.AddSheet("登录分布")
	if err != nil {
		beego.Warn(err)
		return ""
	}

	row = sheet.AddRow()
	row.AddCell().Value = "日期"
	row.AddCell().Value = "时间"
	row.AddCell().Value = "人数"

	loc, _ := time.LoadLocation("Local")
	theTime, _ := time.ParseInLocation("2006-01-02 15:04:05", time.Now().Format("2006-01-02") + " 00:00:00", loc)
	for i := 0; i < len(series); i++ {
		item := series[i]
		for k, v := range item.MapCount {
			row = sheet.AddRow()
			row.AddCell().SetString(item.Name)
			ti := theTime.Add(time.Minute*5*time.Duration(k))
			row.AddCell().SetString(fmt.Sprintf("%02d:%02d:%02d", ti.Hour(), ti.Minute(), ti.Second()))
			row.AddCell().SetInt(v)
		}
	}

	name := fmt.Sprintf("./static/统计-登录-%s.xlsx", user)
	os.Remove(name)
	err = file.Save(name)
	if err != nil {
		beego.Warn(err)
		return ""
	}

	return name
}

// 玩家登录记录
func LoginGetPlayerDayRecords(uid int, date string) RecordLoginArray {
	var dayRecords RecordLoginArray
	f, err := os.Open(fmt.Sprintf("%s/login-%s.log", utils.GetKeyConf("events", "path"), date))
	if err != nil {
		return dayRecords
	}
	defer f.Close()
	
	buff := bufio.NewReader(f)
	for {
		line, err := buff.ReadString('\n')

		if err != nil || io.EOF == err {
			break
		}
		line = strings.TrimSpace(line)

		arr := strings.Split(line, ";")
		_uid := utils.StringToInt(arr[2])
		if uid == _uid {
			info := &RecordLogin{
				EventTime: arr[0],
				ServerId: arr[1],
				Uid: _uid,
				RegisteTime: utils.StringToInt64(arr[3]),
				IP: arr[4],
			}
			dayRecords = append(dayRecords, info)
		}
	}
	return dayRecords
}
func LoginGetPlayerRangeDayRecords(uid int, days int) RecordLoginArray {
	var records RecordLoginArray
	currTime := int(time.Now().Unix())
	dayCount := 0
	for {
		tiEvent := currTime - 86400*dayCount
		date := time.Unix(int64(tiEvent), 0).Format("2006-01-02")

		dayRecords := LoginGetPlayerDayRecords(uid, date)
		records = append(records, dayRecords...)

		dayCount ++
		if dayCount > days {
			break
		}
	}
	return records
}
// IP登录记录
func LoginGetIPDayRecords(ip string, date string) RecordLoginArray {
	var dayRecords RecordLoginArray
	f, err := os.Open(fmt.Sprintf("%s/login-%s.log", utils.GetKeyConf("events", "path"), date))
	if err != nil {
		return dayRecords
	}
	defer f.Close()
	
	buff := bufio.NewReader(f)
	for {
		line, err := buff.ReadString('\n')

		if err != nil || io.EOF == err {
			break
		}
		line = strings.TrimSpace(line)

		arr := strings.Split(line, ";")
		if ip == arr[4] {
			info := &RecordLogin{
				EventTime: arr[0],
				ServerId: arr[1],
				Uid: utils.StringToInt(arr[2]),
				RegisteTime: utils.StringToInt64(arr[3]),
				IP: arr[4],
			}
			dayRecords = append(dayRecords, info)
		}
	}
	return dayRecords
}
func LoginGetIPRangeDayRecords(ip string, days int) RecordLoginArray {
	var records RecordLoginArray
	currTime := int(time.Now().Unix())
	dayCount := 0
	for {
		tiEvent := currTime - 86400*dayCount
		date := time.Unix(int64(tiEvent), 0).Format("2006-01-02")

		dayRecords := LoginGetIPDayRecords(ip, date)
		records = append(records, dayRecords...)

		dayCount ++
		if dayCount > days {
			break
		}
	}
	return records
}