package events

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

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

// 玩家等级分布
func PlayerLevel_get_day_level_count(date string, serverId string) (map[int]int, int) {
	var plCount = make(map[int]int)
	var playerLevel = make(map[int]int)
	
	f, err := os.Open(fmt.Sprintf("%s/event-%s.log", utils.GetKeyConf("events", "path"), date))
	if err != nil {
		return plCount, 0
	}
	defer f.Close()
	
	buff := bufio.NewReader(f)
	maxLevel := 0
	for {
		line, err := buff.ReadString('\n')

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

		arr := strings.Split(line, ";")
		if arr[3] == "player-upgrade" {
			if serverId == "0" || arr[1] == serverId {
				uid := utils.StringToInt(arr[2])
				level := utils.StringToInt(arr[4])
				playerLevel[uid] = level
				if level > maxLevel {
					maxLevel = level
				}
			}
		}
	}

	// 关卡分布
	for _, v := range playerLevel {
		plCount[v] ++
	}
	return plCount, maxLevel
}

func PlayerLevel_get_range_day_level_count(days int, serverId string) ([]*tgSeries, []string) {
	var series []*tgSeries
	currTime := int(time.Now().Unix())
	dayCount := 0
	maxCategories := 0
	for {
		tiEvent := currTime - 86400*dayCount
		date := time.Unix(int64(tiEvent), 0).Format("2006-01-02")
		item := &tgSeries{}
		glCount, maxLevel := PlayerLevel_get_day_level_count(date, serverId)
		item.Name = date
		for i:=0; i <= maxLevel; i++ {
			item.Data = append(item.Data, glCount[i])
		}
		item.MapCount = glCount
		series = append(series, item)

		if maxLevel > maxCategories {
			maxCategories = maxLevel
		}
		// log.Printf("playerlevel date[%s] item[%v]", date, item)
		dayCount ++
		if dayCount > days {
			break
		}
	}
	var arrCate []string
	for i:=0; i < maxCategories + 5; i++ {
		arrCate = append(arrCate, fmt.Sprintf("%d", i))
	}
	// log.Printf("playerlevel series[%v] arrCate[%v]", series, arrCate)
	return series, arrCate
}

// 保存文件
func Save_playerlevel_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 = "人数"

	for i := 0; i < len(series); i++ {
		item := series[i]
		for k, v := range item.MapCount {
			row = sheet.AddRow()
			row.AddCell().SetString(item.Name)
			row.AddCell().SetInt(k)
			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
}