package ctbrec.sites.stripchat;

import static ctbrec.io.HttpConstants.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

import ctbrec.Config;
import ctbrec.Model;
import ctbrec.io.HttpClient;
import ctbrec.io.HttpException;
import ctbrec.sites.AbstractSite;
import okhttp3.Request;
import okhttp3.Response;

public class Stripchat extends AbstractSite {

    public static final String BASE_URI = "https://stripchat.com";
    private HttpClient httpClient;

    @Override
    public String getName() {
        return "Stripchat";
    }

    @Override
    public String getBaseUrl() {
        return BASE_URI;
    }

    @Override
    public String getAffiliateLink() {
        return "https://go.strpjmp.com?creativeId=1&campaignId=1&sourceId=app&path=%2F&userId=cd0bfa6152f1e2b55f8e8218de2f32c7e6c41d9846a390a2113ed4a5edfc95d8";
    }

    @Override
    public String getBuyTokensLink() {
        return getAffiliateLink();
    }

    @Override
    public StripchatModel createModel(String name) {
        StripchatModel model = new StripchatModel();
        model.setName(name);
        model.setUrl(getBaseUrl() + "/" + name);
        model.setSite(this);
        return model;
    }

    @Override
    public Double getTokenBalance() throws IOException {
        if (!credentialsAvailable()) {
            throw new IOException("Account settings not available");
        }

        String username = Config.getInstance().getSettings().camsodaUsername;
        String url = BASE_URI + "/api/v1/user/" + username;
        Request request = new Request.Builder().url(url).build();
        try(Response response = getHttpClient().execute(request)) {
            if(response.isSuccessful()) {
                JSONObject json = new JSONObject(response.body().string());
                if(json.has("user")) {
                    JSONObject user = json.getJSONObject("user");
                    if(user.has("tokens")) {
                        return (double) user.getInt("tokens");
                    }
                }
            } else {
                throw new HttpException(response.code(), response.message());
            }
        }
        throw new RuntimeException("Tokens not found in response");
    }

    @Override
    public synchronized boolean login() throws IOException {
        return credentialsAvailable() && getHttpClient().login();
    }

    @Override
    public HttpClient getHttpClient() {
        if(httpClient == null) {
            httpClient = new StripchatHttpClient();
        }
        return httpClient;
    }

    @Override
    public void init() throws IOException {
        // noop
    }

    @Override
    public void shutdown() {
        if(httpClient != null) {
            httpClient.shutdown();
        }
    }

    @Override
    public boolean supportsTips() {
        return false;
    }

    @Override
    public boolean supportsFollow() {
        return true;
    }

    @Override
    public boolean supportsSearch() {
        return true;
    }

    @Override
    public List<Model> search(String q) throws IOException, InterruptedException {
        String url = BASE_URI + "/api/front/v2/models/search?limit=20&query=" + URLEncoder.encode(q, "utf-8");
        Request req = new Request.Builder()
                .url(url)
                .header(USER_AGENT, Config.getInstance().getSettings().httpUserAgent)
                .build();
        try (Response response = getHttpClient().execute(req)) {
            if (response.isSuccessful()) {
                JSONObject json = new JSONObject(response.body().string());
                if (json.optInt("totalCount") > 0) {
                    List<Model> models = new ArrayList<>();
                    JSONArray results = json.getJSONArray("models");
                    for (int i = 0; i < results.length(); i++) {
                        JSONObject result = results.getJSONObject(i);
                        StripchatModel model = createModel(result.getString("username"));
                        model.setPreview(result.optString("previewUrlThumbBig"));
                        models.add(model);
                    }
                    return models;
                } else {
                    return Collections.emptyList();
                }
            } else {
                throw new HttpException(response.code(), response.message());
            }
        }
    }

    @Override
    public boolean isSiteForModel(Model m) {
        return m instanceof StripchatModel;
    }

    @Override
    public boolean credentialsAvailable() {
        String username = Config.getInstance().getSettings().stripchatUsername;
        return username != null && !username.trim().isEmpty();
    }

    @Override
    public Model createModelFromUrl(String url) {
        Matcher m = Pattern.compile("https?://(?:.*?\\.)?stripchat.com/([^/]*?)/?").matcher(url);
        if (m.matches()) {
            String modelName = m.group(1);
            return createModel(modelName);
        } else {
            return super.createModelFromUrl(url);
        }
    }
}
