package ru.yandex.webmaster3.core.turbo.model;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.base.Strings;
import lombok.AllArgsConstructor;
import lombok.Value;

import ru.yandex.autodoc.common.doc.annotation.Description;

/**
 * Created by Oleg Bazdyrev on 29/08/2017.
 */
@Value
@AllArgsConstructor(onConstructor_ = @JsonCreator)
@JsonIgnoreProperties(ignoreUnknown = true)
public class TurboUrl {

    // TODO временный костыль
    private final static String PREVIEW_SERVICE_URL = "https://yandex.ru/turbo?text=";

    public static final TypeReference<List<TurboUrl>> TYPE_REFERENCE = new TypeReference<>() {
    };
    @Description("URL исходной страницы")
    String url;
    @Description("URL турбо-превьюшки страницы")
    String turboUrl;
    @Description("Заголовок турбо-страницы")
    String title;
    String hash;
    @Description("Удален ли элемент (turbo=false)")
    boolean deleted;

    public TurboUrl withTurboUrlSuffix(String suffix) {
        String turboUrl = this.turboUrl;
        if (Strings.isNullOrEmpty(turboUrl)) {
            turboUrl = PREVIEW_SERVICE_URL + URLEncoder.encode(url, StandardCharsets.UTF_8);
        }
        if (Strings.isNullOrEmpty(suffix) || Strings.isNullOrEmpty(turboUrl)) {
            return this;
        }
        return new TurboUrl(url, turboUrl + suffix, title, hash, deleted);
    }
}
