//           ___   ____               ___       ___
// \ \  / / | _   |  __| \ \  / / || | __  || || _ |
//  \ \/ /  |___  | |__   \ \/ /  || |___  || ||___|
//   \  /   | _   | _  |   \  /   ||  __ | || ||\\
//    \/    |___  |___ |    \/    || ____| || || \\
//
// Copyright (c) 2021 Piotr Biernat. https://pbiernat.dev. MIT License
// Repo: https://git.pbiernat.dev/golang/vegvisir

package cache

import (
	"encoding/json"
	"log"
)

type ResponseCache struct {
	URL  string
	Body string
	// Headers map[string]string
}

type ResponseCacheManager struct {
	datastore CacheDatastore
	prefix    string
	ttl       int
}

func NewResponseCacheManager(datastore CacheDatastore, ttl int) ResponseCacheManager {
	return ResponseCacheManager{
		datastore: datastore,
		prefix:    "response_",
		ttl:       ttl,
	}
}

func (rm *ResponseCacheManager) Save(name string, r ResponseCache) bool {
	if !rm.datastore.IsConnected() {
		log.Println("Response-cache:", "Not connected to server")
		return false
	}

	data, err := json.Marshal(r)
	if err != nil {
		log.Println("Response-cache", "JSON encode:", err)
		return false
	}

	name = rm.prefix + name
	err = rm.datastore.SetKey(name, string(data), rm.ttl)
	if err != nil {
		log.Println("Response-cache:", err, name) // FIXME
		return false
	}

	return true
}

func (rm *ResponseCacheManager) Load(name string) (bool, *ResponseCache) {
	if !rm.datastore.IsConnected() {
		log.Println("Response-cache:", "Not connected to server")
		return false, &ResponseCache{}
	}

	name = rm.prefix + name
	data, err := rm.datastore.GetKey(name)
	if err != nil {
		return false, &ResponseCache{}
	}

	rc := &ResponseCache{}
	err = json.Unmarshal([]byte(data.(string)), &rc)
	if err != nil {
		log.Println("Response-cache:", "JSON docode:", err)
		return false, &ResponseCache{}
	}

	return true, rc
}