package ctbrec.sites.stripchat;

import static ctbrec.Model.State.*;
import static ctbrec.io.HttpConstants.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

import javax.xml.bind.JAXBException;

import org.json.JSONArray;
import org.json.JSONObject;

import com.iheartradio.m3u8.ParseException;
import com.iheartradio.m3u8.PlaylistException;

import ctbrec.AbstractModel;
import ctbrec.Config;
import ctbrec.io.HttpException;
import ctbrec.recorder.download.StreamSource;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class StripchatModel extends AbstractModel {
    private String status = null;
    private int[] resolution = new int[] {0, 0};

    @Override
    public boolean isOnline(boolean ignoreCache) throws IOException, ExecutionException, InterruptedException {
        if (ignoreCache || status == null) {
            JSONObject jsonResponse = loadModelInfo();
            if (jsonResponse.has("user")) {
                JSONObject user = jsonResponse.getJSONObject("user");
                status = user.optString("status");
            }
        }
        boolean online = Objects.equals(status, "public");
        if (online) {
            setOnlineState(ONLINE);
        }
        return online;
    }

    private JSONObject loadModelInfo() throws IOException {
        String url = getSite().getBaseUrl() + "/api/front/users/username/" + URLEncoder.encode(getName(), StandardCharsets.UTF_8.name());
        Request req = new Request.Builder()
                .url(url)
                .header(ACCEPT, MIMETYPE_APPLICATION_JSON)
                .header(ACCEPT_LANGUAGE, Locale.ENGLISH.getLanguage())
                .header(X_REQUESTED_WITH, XML_HTTP_REQUEST)
                .header(USER_AGENT, Config.getInstance().getSettings().httpUserAgent)
                .header(REFERER, getUrl())
                .build();
        try (Response response = site.getHttpClient().execute(req)) {
            if (response.isSuccessful()) {
                JSONObject jsonResponse = new JSONObject(response.body().string());
                return jsonResponse;
            } else {
                throw new HttpException(response.code(), response.message());
            }
        }
    }

    @Override
    public List<StreamSource> getStreamSources() throws IOException, ExecutionException, ParseException, PlaylistException, JAXBException {
        String name = URLEncoder.encode(getName(), StandardCharsets.UTF_8.name());
        String url = getSite().getBaseUrl() + "/api/front/models/username/" + name + "/cam?triggerRequest=loadCam";
        Request req = new Request.Builder()
                .url(url)
                .header(ACCEPT, MIMETYPE_APPLICATION_JSON)
                .header(ACCEPT_LANGUAGE, Locale.ENGLISH.getLanguage())
                .header(X_REQUESTED_WITH, XML_HTTP_REQUEST)
                .header(USER_AGENT, Config.getInstance().getSettings().httpUserAgent)
                .header(REFERER, getUrl())
                .build();
        try (Response response = site.getHttpClient().execute(req)) {
            if (response.isSuccessful()) {
                JSONObject jsonResponse = new JSONObject(response.body().string());
                String streamName = jsonResponse.optString("streamName");
                JSONObject viewServers = jsonResponse.getJSONObject("viewServers");
                String serverName = viewServers.optString("flashphoner-hls");
                JSONObject broadcastSettings = jsonResponse.getJSONObject("broadcastSettings");
                List<StreamSource> sources = new ArrayList<>();
                StreamSource best = new StreamSource();
                best.height = broadcastSettings.optInt("height");
                best.width = broadcastSettings.optInt("width");
                best.mediaPlaylistUrl = "https://b-" + serverName + ".stripst.com/hls/" + streamName + "/" + streamName + ".m3u8";
                sources.add(best);
                Object resolutionObject = broadcastSettings.get("resolutions");
                if (resolutionObject instanceof JSONObject) {
                    JSONObject resolutions = (JSONObject) resolutionObject;
                    JSONArray heights = resolutions.names();
                    for (int i = 0; i < heights.length(); i++) {
                        String h = heights.getString(i);
                        StreamSource streamSource = new StreamSource();
                        streamSource.height = Integer.parseInt(h.replace("p", ""));
                        streamSource.width = streamSource.height * best.getWidth() / best.getHeight();
                        String source = streamName + "-" + streamSource.height + "p";
                        streamSource.mediaPlaylistUrl = "https://b-" + serverName + ".stripst.com/hls/" + source + "/" + source + ".m3u8";
                        sources.add(streamSource);
                    }
                }
                return sources.stream().sorted((a, b) -> a.height - b.height).collect(Collectors.toList());
            } else {
                throw new HttpException(response.code(), response.message());
            }
        }
    }

    @Override
    public void invalidateCacheEntries() {
        status = null;
        resolution = new int[] { 0, 0 };
    }

    @Override
    public void receiveTip(Double tokens) throws IOException {
        // not implemented
    }

    @Override
    public int[] getStreamResolution(boolean failFast) throws ExecutionException {
        if (!failFast) {
            try {
                List<StreamSource> sources = getStreamSources();
                if (!sources.isEmpty()) {
                    StreamSource best = sources.get(sources.size() - 1);
                    resolution = new int[] { best.getWidth(), best.getHeight() };
                }
            } catch (IOException | ParseException | PlaylistException | JAXBException e) {
                throw new ExecutionException(e);
            }
        }
        return resolution;
    }

    @Override
    public boolean follow() throws IOException {
        JSONObject modelInfo = loadModelInfo();
        JSONObject user = modelInfo.getJSONObject("user");
        long modelId = user.optLong("id");

        StripchatHttpClient client = (StripchatHttpClient) getSite().getHttpClient();
        String url = Stripchat.BASE_URI + "/api/front/users/" + client.getUserId() + "/favorites/" + modelId;
        JSONObject requestParams = new JSONObject();
        requestParams.put("csrfToken", client.getCsrfToken());
        requestParams.put("csrfTimestamp", client.getCsrfTimestamp());
        requestParams.put("csrfNotifyTimestamp", client.getCsrfNotifyTimestamp());
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), requestParams.toString());
        Request request = new Request.Builder()
                .url(url)
                .header(ACCEPT, "*/*")
                .header(USER_AGENT, Config.getInstance().getSettings().httpUserAgent)
                .header(ORIGIN, Stripchat.BASE_URI)
                .header(REFERER, Stripchat.BASE_URI + '/' + getName())
                .header(CONTENT_TYPE, MIMETYPE_APPLICATION_JSON)
                .put(body)
                .build();
        try (Response response = client.execute(request)) {
            if (response.isSuccessful()) {
                return true;
            } else {
                throw new HttpException(response.code(), response.message());
            }
        }
    }

    @Override
    public boolean unfollow() throws IOException {
        JSONObject modelInfo = loadModelInfo();
        JSONObject user = modelInfo.getJSONObject("user");
        long modelId = user.optLong("id");
        JSONArray favoriteIds = new JSONArray();
        favoriteIds.put(modelId);

        StripchatHttpClient client = (StripchatHttpClient) getSite().getHttpClient();
        String url = Stripchat.BASE_URI + "/api/front/users/" + client.getUserId() + "/favorites";
        JSONObject requestParams = new JSONObject();
        requestParams.put("favoriteIds", favoriteIds);
        requestParams.put("csrfToken", client.getCsrfToken());
        requestParams.put("csrfTimestamp", client.getCsrfTimestamp());
        requestParams.put("csrfNotifyTimestamp", client.getCsrfNotifyTimestamp());
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), requestParams.toString());
        Request request = new Request.Builder()
                .url(url)
                .header(ACCEPT, MIMETYPE_APPLICATION_JSON)
                .header(USER_AGENT, Config.getInstance().getSettings().httpUserAgent)
                .header(ORIGIN, Stripchat.BASE_URI)
                .header(REFERER, Stripchat.BASE_URI)
                .header(CONTENT_TYPE, MIMETYPE_APPLICATION_JSON)
                .delete(body)
                .build();
        try (Response response = client.execute(request)) {
            if (response.isSuccessful()) {
                return true;
            } else {
                throw new HttpException(response.code(), response.message());
            }
        }
    }
}
