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

import java.util.List;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Value;
import org.joda.time.Duration;

import ru.yandex.webmaster3.storage.importer.model.clear.ImportClearPolicy;
import ru.yandex.webmaster3.storage.importer.model.importing.ImportImportingPolicy;
import ru.yandex.webmaster3.storage.importer.model.init.ImportInitPolicy;
import ru.yandex.webmaster3.storage.importer.model.postprocess.ImportPostprocessPolicy;
import ru.yandex.webmaster3.storage.importer.model.preprocess.ImportPreprocessPolicy;
import ru.yandex.webmaster3.storage.importer.model.switching.ImportSwitchPolicy;


/**
 * Created by Oleg Bazdyrev on 20/09/2020.
 * Описание того, когда начинать, как производить, что делать при импорте
 */
@Value
@AllArgsConstructor(onConstructor_ = @JsonCreator)
@Builder
public class ImportDefinition {

    String id;
    @Builder.Default
    boolean enabled = true;
    String database;
    String tableNamePattern;
    List<ImportColumnDefinition> columns;
    ImportInitPolicy initPolicy;
    ImportPreprocessPolicy preprocessPolicy;
    ImportImportingPolicy importingPolicy;
    ImportPostprocessPolicy postprocessPolicy;
    ImportClearPolicy clearPolicy;
    ImportSwitchPolicy switchPolicy;
    @Builder.Default
    Duration delayOnSuccess = Duration.standardMinutes(30);
    @Builder.Default
    Duration delayOnFailure = Duration.standardHours(2);

    public void validate() {
        Preconditions.checkState(!Strings.isNullOrEmpty(id));
        Preconditions.checkState(!Strings.isNullOrEmpty(database));
        Preconditions.checkState(!Strings.isNullOrEmpty(tableNamePattern));
        if (initPolicy != null) {
            initPolicy.validate();
        }
        if (preprocessPolicy != null) {
            preprocessPolicy.validate();
        }
        if (postprocessPolicy != null) {
            postprocessPolicy.validate();
        }
        if (clearPolicy != null) {
            clearPolicy.validate();
        }
        if (importingPolicy != null) {
            importingPolicy.validate();
        }
        if (switchPolicy != null) {
            switchPolicy.validate();
        }
    }

    public ImportPolicy getImportPolicy(ImportStage stage) {
        switch(stage) {
            case INIT:
                return initPolicy;
            case PREPROCESS:
                return preprocessPolicy;
            case IMPORTING:
                return importingPolicy;
            case POSTPROCESS:
                return postprocessPolicy;
            case CLEAR:
                return clearPolicy;
            case SWITCH:
                return switchPolicy;
            default:
                throw new IllegalStateException("Unexpected stage");
        }
    }
}
