package dareka.processor.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.concurrent.Callable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import dareka.Main;
import dareka.processor.HttpResponseHeader;
import dareka.processor.URLResource;

public class NicoCachingTitleRetriever implements Callable<String> {
	public static Log logger = LogFactory.getLog(NicoCachingTitleRetriever.class);
    private String type;
    private String id;

    public NicoCachingTitleRetriever(String type, String id) {
        this.type = type;
        this.id = id;
    }

    public String call() throws Exception {
        logger.debug("title retrieving start");

        String url = NicoApiUtil.getThumbURL(type, id);
        URLResource r = new URLResource(url);
        // In the general case, proxy must let browser know a redirection,
        // but in this case, behave just as a client.
        r.setFollowRedirects(true);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        r.transferTo(null, bout, null, null);

        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
        new HttpResponseHeader(bin); // skip header

        String title = NicoApiUtil.getThumbTitle(bin);
        logger.debug("title retrieving end (" + title + ")");

        NicoIdInfoCache.getInstance().put(type, id, title);

        return title;
    }
}
