package com.stevesoltys.telegramirc.protocol.telegram.message.decoder.image.impl.imgur;

import com.stevesoltys.telegramirc.configuration.telegram.ImgurDecoderConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.Optional;

/**
 * @author Steve Soltys
 */
@Component
public class ImgurUploader {

    private static final String UPLOAD_ENDPOINT = "https://api.imgur.com/3/image?image={image}";

    private static final String IMAGE_URI_VARIABLE = "image";

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final ImgurDecoderConfiguration configuration;

    private final RestTemplate restTemplate;

    public ImgurUploader(ImgurDecoderConfiguration configuration) {
        this.configuration = configuration;

        restTemplate = new RestTemplate();
    }

    public Optional<String> upload(String imageUrl) {
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        headers.set("Authorization", "Client-ID " + configuration.getApiKey());

        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<ImgurResponse> response;

        try {
            response = restTemplate.exchange(UPLOAD_ENDPOINT, HttpMethod.POST, entity, ImgurResponse.class,
                    Collections.singletonMap(IMAGE_URI_VARIABLE, imageUrl));

        } catch (HttpClientErrorException ex) {
            logger.error("Error while uploading image to Imgur.", ex);
            return Optional.empty();
        }

        ImgurResponse imgurResponse = response.getBody();
        ImgurResponseData responseData = imgurResponse.getResponseData();

        if (responseData == null) {
            return Optional.empty();
        }

        return Optional.ofNullable(responseData.getLink());
    }
}

@@ -308,16 +308,116 @@
 ponent;%0A
+import org.springframework.util.LinkedMultiValueMap;%0Aimport org.springframework.util.MultiValueMap;%0A
 import o
@@ -740,22 +740,8 @@
 mage
-?image=%7Bimage%7D
 %22;%0A%0A
@@ -778,28 +778,29 @@
 g IMAGE_
-URI_VARIABLE
+PARAMETER_KEY
  = %22imag
@@ -1428,25 +1428,172 @@
     
-HttpEntity%3CString
+MultiValueMap%3CString, String%3E body = new LinkedMultiValueMap%3C%3E();%0A        body.add(IMAGE_PARAMETER_KEY, imageUrl);%0A%0A        HttpEntity%3CMultiValueMap%3CString, String%3E
 %3E en
@@ -1616,16 +1616,22 @@
 ntity%3C%3E(
+body, 
 headers)
@@ -1805,84 +1805,8 @@
 lass
-,%0A                    Collections.singletonMap(IMAGE_URI_VARIABLE, imageUrl)
 );%0A%0A

Send image URL in body since the Imgur API was changed without notice