package ctbrec.ui.sites.chaturbate;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ctbrec.Model;
import ctbrec.sites.chaturbate.Chaturbate;
import ctbrec.sites.chaturbate.ChaturbateModelParser;
import ctbrec.ui.SiteUiFactory;
import ctbrec.ui.tabs.PaginatedScheduledService;
import javafx.concurrent.Task;
import okhttp3.Request;

public class ChaturbateUpdateService extends PaginatedScheduledService {

    private static final Logger LOG = LoggerFactory.getLogger(ChaturbateUpdateService.class);
    private String url;
    private boolean loginRequired;
    private Chaturbate chaturbate;

    public ChaturbateUpdateService(String url, boolean loginRequired, Chaturbate chaturbate) {
        this.url = url;
        this.loginRequired = loginRequired;
        this.chaturbate = chaturbate;

        ExecutorService executor = Executors.newSingleThreadExecutor(r -> {
            var 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 {
                if (loginRequired && !chaturbate.credentialsAvailable()) {
                    return Collections.emptyList();
                } else {
                    String pageUrl = ChaturbateUpdateService.this.url + "?page="+page+"&keywords=&_=" + System.currentTimeMillis();
                    LOG.debug("Fetching page {}", pageUrl);
                    if(loginRequired) {
                        SiteUiFactory.getUi(chaturbate).login();
                    }
                    var request = new Request.Builder().url(pageUrl).build();
                    try (var response = chaturbate.getHttpClient().execute(request)) {
                        if (response.isSuccessful()) {
                            List<Model> models = ChaturbateModelParser.parseModels(chaturbate, response.body().string());
                            return models;
                        } else {
                            int code = response.code();
                            throw new IOException("HTTP status " + code);
                        }
                    }
                }
            }
        };
    }

    public void setUrl(String url) {
        this.url = url;
    }

}
