package ru.yandex.webmaster3.storage.importer.model;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.google.common.base.Strings;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Value;
import org.apache.curator.shaded.com.google.common.base.Objects;

import ru.yandex.webmaster3.storage.util.clickhouse2.CHPrimitiveType;

/**
 * Created by Oleg Bazdyrev on 20/09/2020.
 */
@Value
@AllArgsConstructor(onConstructor_ = @JsonCreator)
@Builder
public class ImportColumnDefinition {

    String ytName;
    String chName;
    CHPrimitiveType chType;
    String yqlFunction;
    @Builder.Default
    ImportColumnKind kind = ImportColumnKind.REGULAR;

    public String asYqlExpression() {
        String ytName = "`" + Objects.firstNonNull(this.ytName, this.chName) + "`";
        String chName = "`" + Objects.firstNonNull(this.chName, this.ytName) + "`";
        StringBuilder sb = new StringBuilder();
        if (!Strings.isNullOrEmpty(yqlFunction)) {
            sb.append(String.format(yqlFunction, ytName));
        } else if (!Strings.isNullOrEmpty(ytName)) {
            sb.append(ytName);
        } else {
            throw new IllegalArgumentException("Bad column config");
        }
        sb.append(" as ");
        if (!Strings.isNullOrEmpty(chName)) {
            sb.append(chName);
        } else if (!Strings.isNullOrEmpty(ytName)) {
            sb.append(ytName);
        } else {
            throw new IllegalArgumentException("Bad column config");
        }
        return sb.toString();
    }

    public enum ImportColumnKind {
        KEY_DATE,
        KEY,
        REGULAR,
    }

}
