package ctbrec.sites.amateurtv;

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

import ctbrec.Model;
import ctbrec.io.HttpClient;
import ctbrec.sites.AbstractSite;

public class AmateurTv extends AbstractSite {

    public static final String BASE_URL = "https://en.amateur.tv";

    private AmateurTvHttpClient httpClient;


    @Override
    public void init() throws IOException {
        // nothing to do
    }

    @Override
    public String getName() {
        return "Amateur.tv";
    }

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

    @Override
    public Model createModel(String name) {
        AmateurTvModel model = new AmateurTvModel();
        model.setName(name);
        model.setUrl(BASE_URL + '/' + name);
        model.setDescription("");
        model.setSite(this);
        return model;
    }

    @Override
    public Double getTokenBalance() throws IOException {
        return 0d;
    }

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

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

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

    @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 false;
    }

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

    @Override
    public List<Model> search(String q) throws IOException, InterruptedException {
        return Collections.emptyList();
    }

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

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

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

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