package lib

import (
	"encoding/json"
	"os"
)

const cacheFileName = "cache.json" // Renamed for clarity

type CacheItem struct {
	Fetcher string
	Value   string
}

type Cache struct {
	Items         []CacheItem
	cacheFilePath string // New field to store the full path
}

func NewCache() *Cache {
	return &Cache{
		Items:         make([]CacheItem, 0),
		cacheFilePath: cacheFileName,
	}
}

func (c *Cache) Update(fetcher string, value string) {
	for i := range c.Items {
		if c.Items[i].Fetcher == fetcher {
			c.Items[i].Value = value
			return
		}
	}
	c.Items = append(c.Items, CacheItem{
		Fetcher: fetcher,
		Value:   value,
	})
}

func (c *Cache) Get(fetcher string) (string, bool) {
	for _, item := range c.Items {
		if item.Fetcher == fetcher {
			return item.Value, true
		}
	}
	return "", false
}

func (c *Cache) Has(fetcher string) bool {
	_, found := c.Get(fetcher)
	return found
}

func (c *Cache) IsChanged(fetcher string, value string) bool {
	cachedValue, found := c.Get(fetcher)
	if !found {
		return true
	}

	if cachedValue != value {
		return true
	}

	return false
}

func (c *Cache) TryUpdate(fetcher string, value string) bool {
	if c.IsChanged(fetcher, value) {
		c.Update(fetcher, value)
		return true
	}
	return false
}

func (c *Cache) Load() {
	f, err := os.Open(c.cacheFilePath)
	if err != nil {
		return
	}
	defer f.Close()

	json.NewDecoder(f).Decode(&c.Items)
}

func (c *Cache) Save() {
	f, err := os.Create(c.cacheFilePath)
	if err != nil {
		return
	}
	defer f.Close()

	json.NewEncoder(f).Encode(c.Items)
}
