package ru.yandex.wmconsole.service;

import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.wmconsole.util.FileUtil;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;

/**
 * Passes url to the robot without any checks.
 *
 * @author ailyin
 */
public class CrawlUrlService extends AbstractUrlService {
    private static final Logger log = LoggerFactory.getLogger(CrawlUrlService.class);

    private String crawlurlPath;
    private String crawlurlPath2;

    private String rewriteurlPath;
    private String rewriteurlPath2;

    public void crawlUrl(URL url, boolean rewriteUrl, long uid) throws UserException, InternalException {
        FileUtil.saveToAFile(url.toString(), rewriteUrl ? getRewriteurlPath() : getCrawlurlPath());
        log.debug(url + " was successfully saved to a file" +
                (rewriteUrl ? " (url will be rewritten in robot db)." : "."));

        try {
            String line = url.toString() + " " + System.currentTimeMillis() + " " + uid;
            FileUtil.saveToAFile(line, rewriteUrl ? getRewriteurlLogPath() : getCrawlurlLogPath());
            log.debug(url + " was successfully saved to a log file.");
        } catch (InternalException e) {
            log.error("Failed to save url to a log file.", e);
        }
    }

    private String getCrawlurlPath() {
        return crawlurlPath;
    }

    @Required
    public void setCrawlurlPath(String crawlurlPath) {
        this.crawlurlPath = crawlurlPath;
    }

    private String getCrawlurlLogPath() {
        return crawlurlPath2;
    }

    @Required
    public void setCrawlurlPath2(String crawlurlPath2) {
        this.crawlurlPath2 = crawlurlPath2;
    }

    private String getRewriteurlPath() {
        return rewriteurlPath;
    }

    @Required
    public void setRewriteurlPath(String rewriteurlPath) {
        this.rewriteurlPath = rewriteurlPath;
    }

    private String getRewriteurlLogPath() {
        return rewriteurlPath2;
    }

    @Required
    public void setRewriteurlPath2(String rewriteurlPath2) {
        this.rewriteurlPath2 = rewriteurlPath2;
    }
}
