package eu.eudat.logic.proxy;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;


@RestController
@CrossOrigin
public class Proxy {

    private String allowedHost;

    public Proxy(String allowedHost) throws MalformedURLException {
        this.allowedHost = new URL(allowedHost).getHost();
    }

    public Proxy() {

    }

    @RequestMapping(method = RequestMethod.GET, value = {"/eu/eudat/logic/proxy"}, produces = "application/json")
    public @ResponseBody
    ResponseEntity<Object> proxy(@RequestParam("url") String remoteUrl) {

        StringBuffer response = new StringBuffer();
        URL url;
        try {
            URL tempUrl = new URL(remoteUrl);
//			URI uri = new URI(scheme, userInfo, host, port, path, query, fragment);
            URI uri = new URI(tempUrl.getProtocol(), null, tempUrl.getHost(), tempUrl.getPort(), tempUrl.getPath(), (tempUrl.getQuery() != null) ? URLEncoder.encode(tempUrl.getQuery()) : null, tempUrl.getRef());
            url = uri.toURL();

            if (!url.getHost().equals(allowedHost))
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body("{'reason': 'You are not allowed to eu.eudat.logic.proxy -> " + url.getHost() + "'}");
            //if allowed, proceed
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Accept", "application/vnd.api+json; charset=utf-8");

            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                while ((inputLine = in.readLine()) != null)
                    response.append(inputLine);
                in.close();
                return ResponseEntity.status(HttpStatus.OK).body(response.toString());
            } else {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body("{'reason': 'Remote server responded with: " + responseCode + "'}");
            }

        } catch (IOException | URISyntaxException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{'reason': 'Could not eu.eudat.logic.proxy to given host'}");
        }

    }

}
