package ctbrec.ui.sites.jasmin;

import static ctbrec.io.HtmlParser.*;
import static ctbrec.io.HttpConstants.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ctbrec.Config;
import ctbrec.Model;
import ctbrec.NotLoggedInExcetion;
import ctbrec.io.HttpException;
import ctbrec.sites.jasmin.LiveJasmin;
import ctbrec.sites.jasmin.LiveJasminModel;
import ctbrec.ui.SiteUiFactory;
import ctbrec.ui.tabs.PaginatedScheduledService;
import javafx.concurrent.Task;
import okhttp3.Request;
import okhttp3.Response;

public class LiveJasminFollowedUpdateService extends PaginatedScheduledService {

    private static final Logger LOG = LoggerFactory.getLogger(LiveJasminFollowedUpdateService.class);
    private LiveJasmin liveJasmin;
    private String url;

    public LiveJasminFollowedUpdateService(LiveJasmin liveJasmin) {
        this.liveJasmin = liveJasmin;
        this.url = liveJasmin.getBaseUrl() + "/en/member/favorite";
    }

    @Override
    protected Task<List<Model>> createTask() {
        return new Task<List<Model>>() {
            @Override
            public List<Model> call() throws IOException {
                if (!liveJasmin.credentialsAvailable()) {
                    throw new NotLoggedInExcetion("Credentials missing");
                }

                boolean loggedIn = SiteUiFactory.getUi(liveJasmin).login();
                if (!loggedIn) {
                    throw new NotLoggedInExcetion("Couldn't login to livejasmin");
                }
                LOG.debug("Fetching page {}", url);
                Request request = new Request.Builder()
                        .url(url)
                        .header(USER_AGENT, Config.getInstance().getSettings().httpUserAgent)
                        .header(ACCEPT, "*/*")
                        .header(ACCEPT_LANGUAGE, Locale.ENGLISH.getLanguage())
                        .header(REFERER, liveJasmin.getBaseUrl())
                        .build();
                try (Response response = liveJasmin.getHttpClient().execute(request)) {
                    if (response.isSuccessful()) {
                        String body = response.body().string();
                        List<Model> models = new ArrayList<>();
                        Elements modelCells = getTags(body, "article[class~=perf_container]");
                        for (Element modelCell : modelCells) {
                            String cellHtml = modelCell.html();
                            String name = getText(cellHtml, "span[class~=performer_name_simple]").trim();
                            LiveJasminModel model = (LiveJasminModel) liveJasmin.createModel(name);
                            model.setPreview(getTag(cellHtml, "img[class~=performer-image]").attr("data-jpg-src"));
                            model.setId(getTag(cellHtml, "span[class~=remove][class~=favorite]").attr("data-model-id"));
                            models.add(model);
                        }
                        return models;
                    } else {
                        throw new HttpException(response.code(), response.message());
                    }
                }
            }
        };
    }
}
