package ru.yandex.autotests.directapi.darkside.datacontainers.http.response.tsv;

import org.apache.commons.lang.StringEscapeUtils;
import ru.yandex.autotests.directapi.darkside.exceptions.DarkSideException;
import ru.yandex.autotests.irt.testutils.json.JsonUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author xy6er
 */
public class AllBannersPhraseIdsResponse {
    List<PhraseData> phrases;

    public static class PhraseData {
        Long bid;
        String lastChange;
        boolean archived;

        public PhraseData() {
        }

        public PhraseData(Long bid, String lastChange, boolean archived) {
            this.bid = bid;
            this.lastChange = lastChange;
            this.archived = archived;
        }

        public Long getBid() {
            return bid;
        }

        public void setBid(Long bid) {
            this.bid = bid;
        }

        public String getLastChange() {
            return lastChange;
        }

        public void setLastChange(String lastChange) {
            this.lastChange = lastChange;
        }

        public boolean getArchived() {
            return archived;
        }

        public void setArchived(boolean archived) {
            this.archived = archived;
        }
    }

    public List<PhraseData> getPhrases() {
        return this.phrases;
    }

    public AllBannersPhraseIdsResponse(String tsv) {
        phrases = new ArrayList<>();
        String[] tsvLines = tsv.split("\n");
        Pattern pattern = Pattern.compile("(\\d*)\t(\\d{14})\t((0|1))");
        for (String line : tsvLines) {
            if (!line.equalsIgnoreCase("#end")) {
                line = StringEscapeUtils.unescapeHtml(line);
                Matcher matcher = pattern.matcher(line);
                if (matcher.matches())
                    try {
                        phrases.add(new PhraseData(
                                Long.valueOf(matcher.group(1)),
                                matcher.group(2),
                                matcher.group(3).equals("1")
                        ));
                    } catch (Exception e) {
                        throw new DarkSideException(line, e);
                    }
                else
                    throw new DarkSideException("Ошибка парсинга ответа: не удалось распарсить строку " + line);
            }
        }
    }

    @Override
    public String toString() {
        return JsonUtils.toString(this);
    }
}



