package ru.yandex.wmconsole.service;

import java.net.URL;
import java.util.Map;

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

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

/**
 * Passes url to the fast robot and to the frq filter.
 *
 * @author ailyin
 */
public class ReindexUrlService extends AbstractUrlService {
    private static final Logger log = LoggerFactory.getLogger(ReindexUrlService.class);

    private Map<SearchDomainEnum, String> reindexPath;
    private Map<SearchDomainEnum, String> reindexLogPath;

    public void reindexUrl(URL url, long uid, SearchDomainEnum search) throws InternalException {
        FileUtil.saveToAFile(url.toString(), getReindexurlPath(search));
        log.debug(url + " was successfully saved to a file.");

        try {
            String line = url.toString() + " " + System.currentTimeMillis() + " " + uid;
            FileUtil.saveToAFile(line, getReindexurlLogPath(search));
            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 getReindexurlPath(SearchDomainEnum search) {
        return reindexPath.get(search);
    }

    private String getReindexurlLogPath(SearchDomainEnum search) {
        return reindexLogPath.get(search);
    }

    @Override
    public boolean isIndexed(URL url) throws UserException, InternalException {
        return super.isIndexed(url);
    }

    @Required
    public void setReindexPath(Map<SearchDomainEnum, String> reindexPath) {
        this.reindexPath = reindexPath;
        for (SearchDomainEnum searchDomain : SearchDomainEnum.values()) {
            if (reindexPath.get(searchDomain) == null) {
                throw new IllegalArgumentException("Missing reindex path for domain: " + searchDomain);
            }
        }
    }

    @Required
    public void setReindexLogPath(Map<SearchDomainEnum, String> reindexLogPath) {
        this.reindexLogPath = reindexLogPath;
        for (SearchDomainEnum searchDomain : SearchDomainEnum.values()) {
            if (reindexLogPath.get(searchDomain) == null) {
                throw new IllegalArgumentException("Missing reindex log path for domain: " + searchDomain);
            }
        }
    }
}
