package ctbrec.variableexpansion;

import ctbrec.Config;
import ctbrec.Model;
import ctbrec.ModelGroup;
import ctbrec.StringUtil;
import ctbrec.recorder.Recorder;
import ctbrec.sites.Site;
import ctbrec.variableexpansion.functions.AntlrSyntacErrorAdapter;

import java.util.Optional;
import java.util.UUID;

import static java.util.Optional.ofNullable;

public class ModelVariableExpander extends AbstractVariableExpander {

    public ModelVariableExpander(Model model, Config config, Recorder recorder, AntlrSyntacErrorAdapter errorListener) {
        super(errorListener);
        Optional<ModelGroup> modelGroup = Optional.ofNullable(recorder).flatMap(r -> r.getModelGroup(model));
        placeholderValueSuppliers.put("modelName", ofNullable(model.getName()));
        placeholderValueSuppliers.put("modelDisplayName", ofNullable(model.getDisplayName()));
        placeholderValueSuppliers.put("modelNotes", getSanitizedModelNotes(config, model));
        placeholderValueSuppliers.put("siteName", ofNullable(model).map(Model::getSite).map(Site::getName));
        placeholderValueSuppliers.put("modelGroupName", modelGroup.map(ModelGroup::getName));
        placeholderValueSuppliers.put("modelGroupId", modelGroup.map(ModelGroup::getId).map(UUID::toString));
    }

    public String expand(String input) {
        return fillInPlaceHolders(input, placeholderValueSuppliers);
    }

    private Optional<Object> getSanitizedModelNotes(Config config, Model m) {
        return ofNullable(config.getModelNotes(m)).map(StringUtil::sanitize);
    }
}
