package events

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

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

// 玩家等级分布
func OnlineTime_get_day_time_count(date string, minutes int, serverId string) (map[int]int, int) {
	var timeCount = make(map[int]int)
	
	f, err := os.Open(fmt.Sprintf("%s/logout-%s.log", utils.GetKeyConf("events", "path"), date))
	if err != nil {
		return timeCount, 0
	}
	defer f.Close()
	
	maxIndex := 0
	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 {
			sec := utils.StringToInt(arr[3])
			index := int(math.Ceil(float64(sec)/float64(minutes*60)))
			timeCount[index] ++
			if index > maxIndex {
				maxIndex = index
			}
		}
	}

	return timeCount, maxIndex
}

func OnlineTime_get_range_day_time_count(days int, minutes 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")
		// m, _ := time.ParseDuration("1m")

		item := &tgSeries{}
		item.Name = date
		glCount, maxIndex := OnlineTime_get_day_time_count(date, minutes, serverId)
		for i:=0; i <= maxIndex; i++ {
			item.Data = append(item.Data, glCount[i])
		}
		item.MapCount = glCount
		// log.Printf("item[%v]", item)
		series = append(series, item)

		if maxIndex > maxCategories {
			maxCategories = maxIndex
		}
		dayCount ++
		if dayCount > days {
			break
		}
	}
	
	var arrCate []string
	for i:=0; i < maxCategories + 5; i++ {
		arrCate = append(arrCate, fmt.Sprintf("%d分钟", i*minutes))
	}
	return series, arrCate
}

// 保存文件
func Save_onlinetime_records(series []*tgSeries, minutes int, 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().SetString(fmt.Sprintf("%d分钟", k*minutes))
			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 ""
	}
	// log.Printf("Save_onlinetime_records minutes[%d]", minutes)

	return name
}