package icslog

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

//returns created log file numnber in today
func (l *IcsLog) getTodayLogFileNum() int {
	dir := filepath.Dir(l.LogFileName)
	files, rerr := os.ReadDir(dir)
	if rerr != nil {
		return 0
	}
	iter := 0
	for _, file := range files {
		if !file.IsDir() {
			if strings.Contains(file.Name(), filepath.Base(l.LogFileName)) {
				iter++
			}
		}
	}

	if iter > MAX_LOG_ROTATE_NUM {
		return 0
	}

	return iter
}

func (l *IcsLog) shiftLogFiles(filenum int) {
	dir := filepath.Dir(l.LogFileName)
	files, rerr := os.ReadDir(dir)
	if rerr != nil {
		return
	}

	//l.M.Lock()
	remFileNum := filenum
	filesLen := len(files) - 1
	for file := files[filesLen]; ; file = files[filesLen] {
		if !file.IsDir() {
			//fmt.Println(">>333", file.Name(), filepath.Base(l.LogFileName))
			if strings.Contains(file.Name(), filepath.Base(l.LogFileName)) {
				//fmt.Println(filesLen, file.Name())
				old := fmt.Sprintf("%s/%s", dir, file.Name())
				//fmt.Println(old)
				new := fmt.Sprintf("%s.%02d", l.LogFileName, remFileNum)
				//fmt.Println(new)
				os.Rename(old, new)
				remFileNum--
				if remFileNum < 0 {
					//fmt.Println(">666")
					break
				}
				//fmt.Println(">444")
			}
		}
		filesLen--
		if filesLen < 0 {
			break
		}
	}
	//l.M.Unlock()
}

func (l *IcsLog) checkLogRotate() bool {
	return l.isRotate
}
