package ru.yandex.wmconsole.util.file.comparator.impl;

import ru.yandex.wmconsole.util.file.comparator.TextFileReader;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.InternalProblem;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.servantlet.AbstractServantlet;

import java.io.*;
import java.net.URL;

/**
 * User: azakharov
 * Date: 31.07.13
 * Time: 18:40
 */
public class UrlFileReader implements TextFileReader<UrlRecord> {

    private BufferedReader reader;
    private UrlFactory factory;

    public UrlFileReader(final String fileName, UrlFactory factory) throws FileNotFoundException {
        FileInputStream stream = new FileInputStream(fileName);
        reader = new BufferedReader(new InputStreamReader(stream));
        this.factory = factory;
    }

    /**
     * Get next url record
     *
     * @return next url record in file or null if end of file reached
     */
    @Override
    public UrlRecord next() throws InternalException, UserException {
        String line;
        try {
            line = reader.readLine();
        } catch (IOException e) {
            throw new InternalException(InternalProblem.READ_FILE_ERROR, "readLine error", e);
        }
        if (line == null || line.isEmpty()) {
            return null;
        }

        String[] tokens = line.split("\\t");
        if (tokens.length < 2) {
            throw new InternalException(InternalProblem.READ_FILE_ERROR, "Bad file format: " + line);
        }

        URL url = AbstractServantlet.prepareUrl(tokens[0], false);
        Integer httpCode = null;
        if (tokens.length == 2) {
            try {
                httpCode = Integer.valueOf(tokens[1]);
            } catch (NumberFormatException e) {
            }
        }

        return factory.createRecord(url, UrlSourceEnum.ROBOT, UrlProblemEnum.BAD_HTTP_CODE, httpCode);
    }
}
