package ctbrec.ui.sites.cam4;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

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

import ctbrec.Model;
import ctbrec.io.HttpException;
import ctbrec.sites.cam4.Cam4;
import ctbrec.sites.cam4.Cam4Model;
import ctbrec.ui.SiteUiFactory;
import ctbrec.ui.tabs.PaginatedScheduledService;
import javafx.concurrent.Task;
import okhttp3.Request;
import okhttp3.Response;

public class Cam4FollowedUpdateService extends PaginatedScheduledService {

    private Cam4 site;
    private boolean showOnline = true;

    public Cam4FollowedUpdateService(Cam4 site) {
        this.site = site;
        ExecutorService executor = Executors.newSingleThreadExecutor(r -> {
            Thread t = new Thread(r);
            t.setDaemon(true);
            t.setName("ThumbOverviewTab UpdateService");
            return t;
        });
        setExecutor(executor);
    }

    @Override
    protected Task<List<Model>> createTask() {
        return new Task<List<Model>>() {
            @Override
            public List<Model> call() throws IOException {
                // login first
                SiteUiFactory.getUi(site).login();
                List<Model> models = new ArrayList<>();
                String url = site.getBaseUrl() + "/directoryCams?directoryJson=true&online=" + showOnline + "&url=true&friends=true&favorites=true&resultsPerPage=90";
                Request req = new Request.Builder().url(url).build();
                try (Response response = site.getHttpClient().execute(req)) {
                    if (response.isSuccessful()) {
                        String content = response.body().string();
                        JSONObject json = new JSONObject(content);
                        JSONArray users = json.getJSONArray("users");
                        for (int i = 0; i < users.length(); i++) {
                            JSONObject modelJson = users.getJSONObject(i);
                            String username = modelJson.optString("username");
                            Cam4Model model = site.createModel(username);
                            model.setPreview(modelJson.optString("snapshotImageLink"));
                            model.setOnlineStateByShowType(modelJson.optString("showType"));
                            model.setDescription(modelJson.optString("statusMessage"));
                            if (modelJson.has("hlsPreviewUrl")) {
                                model.setPlaylistUrl(modelJson.getString("hlsPreviewUrl"));
                            }
                            models.add(model);
                        }
                        return models;
                    } else {
                        throw new HttpException(response.code(), response.message());
                    }
                }
            }
        };
    }

    public void setShowOnline(boolean online) {
        this.showOnline = online;
    }
}
