/*
 * Copyright 2017 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.uberfire.ext.metadata.backend.elastic.metamodel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.uberfire.ext.metadata.backend.elastic.index.ElasticSearchIndexProvider;
import org.uberfire.ext.metadata.model.KObject;
import org.uberfire.ext.metadata.model.KProperty;
import org.uberfire.ext.metadata.model.schema.MetaObject;
import org.uberfire.ext.metadata.model.schema.MetaProperty;
import org.uberfire.java.nio.file.Option;

public class ElasticSearchMappingStore {

    private final ElasticSearchIndexProvider indexProvider;

    public ElasticSearchMappingStore(ElasticSearchIndexProvider indexProvider) {
        this.indexProvider = indexProvider;
    }

    public void updateMetaModel(KObject object,
                                MetaObject metaObject) {

        List<MetaProperty> dirtyProperties = new ArrayList<>();
        Optional<MappingMetaData> mappingOptional = this.indexProvider.getMapping(object.getClusterId(),
                                                                                  object.getType().getName());
        if (!mappingOptional.isPresent()) {
            this.indexProvider.putMapping(object.getClusterId(),
                                          object.getType().getName(),
                                          metaObject);
        } else {
            Map<String, Object> mapping = mappingOptional.get().getSourceAsMap();
            Optional.ofNullable(object.getProperties())
                    .ifPresent(kProperties -> {
                        for (final KProperty property : object.getProperties()) {
                            Object config = mapping.get(property.getName());
                            if (config == null) {
                                Optional<MetaProperty> prop = metaObject.getProperty(property.getName());
                                prop.ifPresent(metaProperty -> dirtyProperties.add(metaProperty));
                            }
                        }
                    });

            this.indexProvider.putMapping(object.getClusterId(),
                                          object.getType().getName(),
                                          dirtyProperties);
        }
    }
}
