/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.apache.atlas.services;

import com.google.common.collect.ImmutableList;
import org.apache.atlas.AtlasException;
import org.apache.atlas.typesystem.TypesDef;
import org.apache.atlas.typesystem.json.TypesSerialization;
import org.apache.atlas.typesystem.types.*;
import org.apache.atlas.typesystem.types.utils.TypesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class ReservedTypesRegistrar implements IBootstrapTypesRegistrar {

    private static final Logger LOG = LoggerFactory.getLogger(ReservedTypesRegistrar.class);

    static String getTypesDir() {
        return System.getProperty("atlas.home")+ File.separator+"models";
    }

    @Override
    public void registerTypes(String typesDirName, TypeSystem typeSystem, MetadataService metadataService)
            throws AtlasException {
        File typesDir = new File(typesDirName);
        if (!typesDir.exists()) {
            LOG.info("No types directory {} found - not registering any reserved types", typesDirName);
            return;
        }

        File[] typeDefFiles = typesDir.listFiles();
        //TODO - Enforce a dependency order among models registered by definition and not by modifiedTime as below
        // Workaround - Sort by modifiedTime to get the dependency of models in the right order - first hdfs, followed by hive and hive is needed by storm, falcon models.
        // Sorting them by time will ensure the right order since the modules are in the correct order in pom.
        Arrays.sort(typeDefFiles, new Comparator<File>() {
            public int compare(File f1, File f2) {
                return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
            }
        });

        for (File typeDefFile : typeDefFiles) {
            try {
                if (typeDefFile.isFile()) {
                    String typeDefJSON = new String(Files.readAllBytes(typeDefFile.toPath()), StandardCharsets.UTF_8);
                    registerType(typeSystem, metadataService, typeDefFile.getAbsolutePath(), typeDefJSON);
                }
            } catch (IOException e) {
                LOG.error("error while registering types in file " + typeDefFile.getAbsolutePath(), e);
            } catch (AtlasException e) {
                LOG.error("error while registering types in file " + typeDefFile.getAbsolutePath(), e);
                throw e;
            }
        }

    }

    void registerType(TypeSystem typeSystem, MetadataService metadataService, String typeDefName, String typeDefJSON)
            throws AtlasException {
        TypesDef typesDef = null;
        try {
            typesDef = TypesSerialization.fromJson(typeDefJSON);
        } catch (Exception e) {
            LOG.error("Error while deserializing JSON in {}", typeDefName);
            throw new ReservedTypesRegistrationException("Error while deserializing JSON in " + typeDefName, e);
        }
        List<HierarchicalTypeDefinition<ClassType>> createClassDefList = new ArrayList<>();
        List<HierarchicalTypeDefinition<TraitType>> createTraitDefList = new ArrayList<>();
        List<EnumTypeDefinition> createEnumDefList = new ArrayList<>();
        List<StructTypeDefinition> createStructDefList = new ArrayList<>();

        for(HierarchicalTypeDefinition<ClassType> classTypeDef:typesDef.classTypesAsJavaList()){
            if(!typeSystem.isRegistered(classTypeDef.typeName)){
                LOG.debug("ClassType {} is not registered. Adding to create type list", classTypeDef.typeName);
                createClassDefList.add(classTypeDef);
            }
        }

        for(HierarchicalTypeDefinition<TraitType> traitTypeDef:typesDef.traitTypesAsJavaList()){
            if(!typeSystem.isRegistered(traitTypeDef.typeName)){
                LOG.debug("TraitType {} is not registered. Adding to create type list", traitTypeDef.typeName);
                createTraitDefList.add(traitTypeDef);
            }
        }

        for(StructTypeDefinition structTypeDef:typesDef.structTypesAsJavaList()){
            if(!typeSystem.isRegistered(structTypeDef.typeName)){
                LOG.debug("StructType {} is not registered. Adding to create type list", structTypeDef.typeName);
                createStructDefList.add(structTypeDef);
            }
        }

        for(EnumTypeDefinition enumTypeDef:typesDef.enumTypesAsJavaList()){
            if(!typeSystem.isRegistered(enumTypeDef.name)){
                LOG.debug("EnumType {} is not registered. Adding to create type list", enumTypeDef.name);
                createEnumDefList.add(enumTypeDef);
            }
        }

        TypesDef createTypes = TypesUtil.getTypesDef(ImmutableList.copyOf(createEnumDefList), ImmutableList.copyOf(createStructDefList),
                ImmutableList.copyOf(createTraitDefList), ImmutableList.copyOf(createClassDefList));

        if (! createTypes.isEmpty()) {
            String createTypeJSON = TypesSerialization.toJson(createTypes);
            if (createTypeJSON != null) {
                metadataService.createType(createTypeJSON);
                LOG.info("Created types definition JSON {}", createTypeJSON);
            }
        }
    }
}
