package ru.yandex.webmaster3.validator.common.wsw.model;

import ru.yandex.webmaster3.core.validator.model.ErrorDescription;
import ru.yandex.common.util.collections.Cu;
import ru.yandex.common.util.json.JsonConvertable;
import ru.yandex.common.util.json.Jsoner;
import ru.yandex.common.util.xml.Tagable;
import ru.yandex.common.util.xml.Xmler;

import java.util.List;

import static java.util.Collections.emptyList;
import static java.util.Collections.unmodifiableList;

/**
 * Created by sunlight on 25.02.16.
 */
public class WswErrorDescription implements Tagable, JsonConvertable {

    private final static int MAX_ERRORS = 5;
    private final List<ErrorDescription> errors;

    public WswErrorDescription(List<ErrorDescription> errors) {
        this.errors = errors;
    }

    @Override
    public void toJson(StringBuilder storage) {
        if (errors.isEmpty()) {
            Jsoner.pair("result", "ok").toJson(storage);
        } else {
            final List<JsonConvertable> heads = subList(errors, MAX_ERRORS);
            final Jsoner.JsonArray jsonArray = Jsoner.arrayOfJsons(heads);

            final Jsoner.JsonPair p1 = Jsoner.pair("errors", jsonArray);
            final Jsoner.JsonPair p2 = Jsoner.pair("count", errors.size());
            Jsoner.object(p1, p2).toJson(storage);
        }
    }

    @Override
    public Xmler.Tag asTag() {
        if (errors.isEmpty()) {
            return Xmler.tag("ok");
        } else {
            return Xmler.tag(
                    "errors",
                    Xmler.attribute("count", errors.size()),
                    Cu.head(errors, MAX_ERRORS)
            );
        }
    }

    public void toXml(StringBuilder storage) {
        asTag().toXml(storage);
    }

    private List<JsonConvertable> subList(final List<ErrorDescription> list, final int count) {
        if (list.isEmpty()) {
            return emptyList();
        }
        return unmodifiableList(list.subList(0, Math.min(count, list.size())));
    }
}
