package ru.yandex.autodoc.wmtools.params.fetch.impl;

import ru.yandex.autodoc.common.doc.ExtraInfoItem;
import ru.yandex.autodoc.common.doc.abstracts.ParamsDocRegistrar;
import ru.yandex.autodoc.common.doc.params.ParamType;
import ru.yandex.autodoc.wmtools.params.fetch.impl.common.AbstractParamView;
import ru.yandex.autodoc.wmtools.params.fetch.impl.common.ErrorListener;
import ru.yandex.autodoc.wmtools.util.Strings;
import ru.yandex.autodoc.wmtools.errors.CommonUserException;

import java.util.ArrayList;
import java.util.List;

/**
 * @author avhaliullin
 */
public class StringViewSingle extends AbstractParamView<String> {
    private final Integer minLength;
    private final Integer maxLength;
    private final boolean trim;
    private final boolean normalizeSpaces;
    private final boolean escapeHTML;

    public StringViewSingle(ParamsDocRegistrar registrar, String name, boolean required, String defaultValue,
                            Integer minLength, Integer maxLength, boolean trim, boolean normalizeSpaces, boolean emptyAsNull,
                            boolean escapeHTML, String desc) {
        super(registrar, name, ParamType.STRING, emptyAsNull, required, defaultValue, desc,
                makeExtras(minLength, maxLength, escapeHTML));
        this.minLength = minLength;
        this.maxLength = maxLength;
        this.trim = trim;
        this.normalizeSpaces = normalizeSpaces;
        this.escapeHTML = escapeHTML;
    }

    private static List<ExtraInfoItem> makeExtras(Integer minLength, Integer maxLength, boolean escapeHTML) {
        List<ExtraInfoItem> res = new ArrayList<>();
        if (minLength != null) {
            res.add(ExtraInfoItem.createSimple("Min value length: " + minLength));
        }
        if (maxLength != null) {
            res.add(ExtraInfoItem.createSimple("Max value length: " + maxLength));
        }
        if (escapeHTML) {
            res.add(ExtraInfoItem.createSimple("Escapes HTML"));
        }
        return res;
    }

    @Override
    protected String doFetch(String value, ErrorListener errorListener) {
        if (trim) {
            value = value.trim();
        }
        if (normalizeSpaces) {
            value = Strings.normalizeSpaces(value);
        }
        if (escapeHTML) {
            value = Strings.escapeXSS(value);
        }
        if (minLength != null && value.length() < minLength) {
            errorListener.error(CommonUserException.createValueTooShort(name, value, minLength));
        }
        if (maxLength != null && value.length() > maxLength) {
            errorListener.error(CommonUserException.createValueTooLong(name, value, maxLength));
        }
        return value;
    }
}