package riomhaire.lti.core.infrastructure.facades.configuration.tool;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import riomhaire.lti.core.model.configuration.ToolConfiguration;
import riomhaire.lti.core.model.interfaces.NoKeyResolver;

import java.util.Optional;

/**
 * This reads this tools configuration
 */
public class RedisBasedToolConfigurationResolver  implements NoKeyResolver<Optional<ToolConfiguration>> {

    final ObjectMapper objectMapper = new ObjectMapper();
    private final RedisTemplate<String, String> template;
   // This is what key to lookup
    private  String key = "lti-tool-configuration";
    // Logger
    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * All args constructor

     * @param template THe spring redis template
     * @param redisKey the key in redis where config is stored.
     */
    public RedisBasedToolConfigurationResolver(RedisTemplate<String, String> template,String redisKey) {
        this.template = template;
        this.key=redisKey;
    }

    /**
     * Return information associated with the implementor
     *
     * @return object if found
     */
    @Override
    public Optional<ToolConfiguration> lookup() {
        try {
            var blob = template.opsForValue().get(key);

            if (blob != null) {
                return Optional.of(objectMapper.readValue(blob, ToolConfiguration.class));
            }

        } catch(Exception e) {
          log.error(e.getMessage());
          // return empty
        }
        return Optional.empty();

    }
}
