package ru.yandex.wmconsole.service;

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

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

/**
 * @author aherman
 */
public class DelUrlLogService {
    private static final Logger log = LoggerFactory.getLogger(DelUrlLogService.class);

    private String delurlPath;
    private String delurlLogPath;

    public void logUrl(DelUrlRequest delUrlRequest) throws InternalException {
        addToLog(delUrlRequest);

        try {
            addToAntispamLog(delUrlRequest);
        } catch (InternalException e) {
            log.error("Failed to save url to a log file.", e);
        }

    }

    private void addToAntispamLog(DelUrlRequest delUrlRequest) throws InternalException {
        String line = delUrlRequest.getUrl() + " " +
                System.currentTimeMillis() + " " +
                delUrlRequest.getFrontIp() + " " +
                getOrEmpty(delUrlRequest);
        FileUtil.saveToAFile(line, delurlLogPath);
        log.debug(delUrlRequest.getUrl() + " was successfully saved to a log file.");
    }

    private void addToLog(DelUrlRequest delUrlRequest) throws InternalException {
        FileUtil.saveToAFile(delUrlRequest.getUrl().toString(), delurlPath);
        log.debug(delUrlRequest.getUrl() + " was successfully saved to a file.");
    }

    private String getOrEmpty(DelUrlRequest delUrlRequest) {
        return ((delUrlRequest.getUserId() == null) ? "-" : String.valueOf(delUrlRequest.getUserId()));
    }

    @Required
    public void setDelurlPath(String delurlPath) {
        this.delurlPath = delurlPath;
    }

    @Required
    public void setDelurlLogPath(String delurlLogPath) {
        this.delurlLogPath = delurlLogPath;
    }


}
