package net.runelite.client.rs;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Response;
import okhttp3.ResponseBody;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;

public class OkHttpFileUrlHandler implements Interceptor {

    private static final String fileSystemMarkerHost = "filesystem.local";
    private static final String fileSystemMarkerPrefix = "http://" + fileSystemMarkerHost;

    public static String rewrittenIfFileSchemeUrl(String url) {
        if (url.startsWith("file:")) {
            return url.replaceFirst("file:", fileSystemMarkerPrefix);
        }
        return url;
    }

    private static String restoreFileUrl(String markedFakeHttpUrl) {
        return markedFakeHttpUrl.replaceFirst(fileSystemMarkerPrefix, "file:");
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        okhttp3.Request request = chain.request();
        okhttp3.HttpUrl url = request.url();

        if (!url.host().equals(fileSystemMarkerHost)) {
            return chain.proceed(request);
        }

        String fileUrl = restoreFileUrl(url.toString());
        try {
            byte[] fileContents = new URL(fileUrl).openStream().readAllBytes();
            return new Response.Builder()
                    .body(ResponseBody.create(MediaType.parse("application/octet-stream"), fileContents))
                    .code(200)
                    .message("Some file")
                    .protocol(Protocol.HTTP_1_0)
                    .request(request)
                    .build();
        } catch (FileNotFoundException e) {
            return new Response.Builder()
                    .body(ResponseBody.create(MediaType.parse("text/plain"), new byte[0]))
                    .code(404)
                    .message("File not found (" + fileUrl + ")")
                    .protocol(Protocol.HTTP_1_0)
                    .request(request)
                    .build();
        }

    }
}
