package ctbrec.sites.stripchat;

import ctbrec.Config;
import ctbrec.StringUtil;
import ctbrec.io.HttpClient;
import ctbrec.io.HttpException;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLDecoder;

import static ctbrec.io.HttpConstants.*;
import static java.nio.charset.StandardCharsets.UTF_8;

@Slf4j
public class StripchatHttpClient extends HttpClient {

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private long userId;

    @Getter
    private String csrfToken;
    @Getter
    private String csrfTimestamp;
    @Getter
    private String csrfNotifyTimestamp;
    @Getter
    private String jwtToken;

    public StripchatHttpClient(Config config) {
        super("stripchat", config);
    }

    @Override
    public boolean login() throws IOException {
        if (loggedIn) {
            if (csrfToken == null) {
                loadCsrfToken();
            }
            return true;
        }

        // persisted cookies might let us log in
        if (checkLoginSuccess()) {
            loggedIn = true;
            log.debug("Logged in with cookies");
            if (csrfToken == null) {
                loadCsrfToken();
            }
            return true;
        }

        if (csrfToken == null) {
            loadCsrfToken();
        }

        String url = Stripchat.getBaseUri() + "/api/front/auth/login";
        JSONObject requestParams = new JSONObject();
        requestParams.put("loginOrEmail", config.getSettings().stripchatUsername);
        requestParams.put("password", config.getSettings().stripchatPassword);
        requestParams.put("remember", true);
        requestParams.put("csrfToken", csrfToken);
        requestParams.put("csrfTimestamp", csrfTimestamp);
        requestParams.put("csrfNotifyTimestamp", csrfNotifyTimestamp);
        RequestBody body = RequestBody.Companion.create(requestParams.toString(), JSON);
        Request request = new Request.Builder()
                .url(url)
                .header(ACCEPT, MIMETYPE_APPLICATION_JSON)
                .header(USER_AGENT, config.getSettings().httpUserAgent)
                .header(ORIGIN, Stripchat.getBaseUri())
                .header(REFERER, Stripchat.getBaseUri())
                .header(CONTENT_TYPE, MIMETYPE_APPLICATION_JSON)
                .post(body)
                .build();
        try (Response response = execute(request)) {
            if (response.isSuccessful()) {
                JSONObject resp = new JSONObject(response.body().string());
                if (resp.has("user")) {
                    JSONObject user = resp.getJSONObject("user");
                    userId = user.optLong("id");
                    return true;
                } else {
                    return false;
                }
            } else {
                log.info("Auto-Login failed: {} {} {}", response.code(), response.message(), url);
                return false;
            }
        }
    }

    private void loadCsrfToken() throws IOException {
        String url = Stripchat.getBaseUri() + "/api/front/v2/config/data?requestPath=%2F&timezoneOffset=0";
        Request request = new Request.Builder()
                .url(url)
                .header(ACCEPT, MIMETYPE_APPLICATION_JSON)
                .header(USER_AGENT, config.getSettings().httpUserAgent)
                .header(ORIGIN, Stripchat.getBaseUri())
                .header(REFERER, Stripchat.getBaseUri())
                .header(CONTENT_TYPE, MIMETYPE_APPLICATION_JSON)
                .build();
        try (Response response = execute(request)) {
            if (response.isSuccessful()) {
                JSONObject resp = new JSONObject(response.body().string());
                JSONObject data = resp.getJSONObject("data");
                csrfToken = data.optString("csrfToken");
                csrfTimestamp = data.optString("csrfTimestamp");
                csrfNotifyTimestamp = data.optString("csrfNotifyTimestamp");
            } else {
                throw new HttpException(response.code(), response.message());
            }
        }
    }

    private void loadJwtToken() throws IOException {
        String url = Stripchat.getBaseUri() + "/api/front/v2/config?requestPath=%2F&timezoneOffset=0";
        Request request = new Request.Builder()
                .url(url)
                .header(ACCEPT, MIMETYPE_APPLICATION_JSON)
                .header(USER_AGENT, config.getSettings().httpUserAgent)
                .header(ORIGIN, Stripchat.getBaseUri())
                .header(REFERER, Stripchat.getBaseUri())
                .header(CONTENT_TYPE, MIMETYPE_APPLICATION_JSON)
                .build();
        try (Response response = execute(request)) {
            if (response.isSuccessful()) {
                JSONObject resp = new JSONObject(response.body().string());
                JSONObject config = resp.getJSONObject("config");
                jwtToken = config.optString("jwtToken");
            } else {
                throw new HttpException(response.code(), response.message());
            }
        }
    }

    /**
     * check, if the login worked
     */
    public boolean checkLoginSuccess() throws IOException {
        try {
            loadJwtToken();
        } catch (Exception e) {
            log.info("Login check returned unsuccessful: {}", e.getLocalizedMessage());
            jwtToken = "";
            return false;
        }
        return StringUtil.isNotBlank(jwtToken);
    }

    public long getUserId() throws JSONException, IOException {
        if (userId == 0) {
            String url = Stripchat.getBaseUri() + "/api/front/users/username/" + config.getSettings().stripchatUsername;
            Request request = new Request.Builder()
                    .url(url)
                    .header(ACCEPT, MIMETYPE_APPLICATION_JSON)
                    .header(USER_AGENT, config.getSettings().httpUserAgent)
                    .header(ORIGIN, Stripchat.getBaseUri())
                    .header(REFERER, Stripchat.getBaseUri())
                    .header(CONTENT_TYPE, MIMETYPE_APPLICATION_JSON)
                    .build();
            try (Response response = execute(request)) {
                if (response.isSuccessful()) {
                    JSONObject resp = new JSONObject(response.body().string());
                    JSONObject user = resp.getJSONObject("user");
                    userId = user.optLong("id");
                } else {
                    throw new HttpException(url, response.code(), response.message());
                }
            }
        }
        return userId;
    }

    public JSONObject getAmpl() {
        try {
            Cookie cookie = getCookieJar().getCookie(HttpUrl.parse(Stripchat.getBaseUri()), "baseAmpl");
            String json = URLDecoder.decode(cookie.value(), UTF_8);
            JSONObject ampl = new JSONObject(json);
            return ampl;
        } catch (Exception ex) {
            return new JSONObject();
        }
    }
}
