package cache

import (
	"errors"
	"io/ioutil"
	"os"
	"path/filepath"
	"sync"
)

var cacheLock = sync.Mutex{}
var listCachePath []string

type FileCache struct {
	dirName string
	size    int
}

func NewFileCache(dirName string, size int) *FileCache {
	listCachePath = []string{}
	return &FileCache{
		dirName: dirName,
		size:    size,
	}
}

func (f *FileCache) SetData(key string, data []byte) error {
	if len(key) < 2 {
		return errors.New("key长度最少2")
	}

	cacheLock.Lock()
	defer cacheLock.Unlock()

	//提取目录
	subDir := key[0:2]
	keyFilePath := f.dirName + "/" + subDir + "/" + key

	//判断是否超过size了
	if len(listCachePath) >= f.size && f.size > 0 {
		//获取第一个
		removePath := listCachePath[0]
		_ = os.Remove(removePath)

		//删除第一个
		listCachePath = listCachePath[1:]
	}

	listCachePath = append(listCachePath, keyFilePath)

	_ = os.Mkdir(f.dirName+"/"+subDir, os.ModePerm)

	err := ioutil.WriteFile(keyFilePath, data, 0666)
	return err
}

func (f *FileCache) GetData(key string) ([]byte, error) {
	if len(key) < 2 {
		return nil, errors.New("key长度最少2")
	}

	cacheLock.Lock()
	defer cacheLock.Unlock()

	subDir := key[0:2]
	keyFilePath := f.dirName + "/" + subDir + "/" + key

	return ioutil.ReadFile(keyFilePath)
}

func (f *FileCache) ClearCache() error {
	cacheLock.Lock()
	defer cacheLock.Unlock()

	d, err := os.Open(f.dirName)
	if err != nil {
		return err
	}
	defer d.Close()
	names, err := d.Readdirnames(-1)
	if err != nil {
		return err
	}
	for _, name := range names {
		err = os.RemoveAll(filepath.Join(f.dirName, name))
		if err != nil {
			return err
		}
	}
	return nil
}
