/*
 * Copyright © 2009 HotPads (admin@hotpads.com)
 *
 * 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 io.datarouter.storage.serialize.fieldcache;

import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;

import io.datarouter.model.databean.Databean;
import io.datarouter.model.exception.DataAccessException;
import io.datarouter.model.field.Field;
import io.datarouter.model.key.primary.PrimaryKey;
import io.datarouter.util.lang.ReflectionTool;

public class FieldGeneratorTool{

	private static final int MAX_RANDOM_ID_GENERATION_ATTEMPTS = 10;

	public static <PK extends PrimaryKey<PK>,D extends Databean<PK,D>> void generateAndSetValueForFieldIfNecessary(
			PhysicalDatabeanFieldInfo<PK,D,?> fieldInfo, D databean){
		optFieldToGenerate(fieldInfo, databean)
				.ifPresent(field -> generateAndSetValueForField(fieldInfo, databean, field, bean -> true));
	}

	public static <PK extends PrimaryKey<PK>,D extends Databean<PK,D>> void generateAndSetValueForField(
		PhysicalDatabeanFieldInfo<PK,D,?> fieldInfo, D databean, Field<?> field, Predicate<D> valueChecker){
		int attempts = 0;
		while(attempts++ < MAX_RANDOM_ID_GENERATION_ATTEMPTS){
			setAutoGeneratedId(fieldInfo, databean, field.getKey().generateRandomValue());
			if(valueChecker.test(databean)){
				return;
			}
		}
		throw new DataAccessException("error generating random id for " + fieldInfo.getTableName());
	}

	public static void setAutoGeneratedId(DatabeanFieldInfo<?,?,?> fieldInfo, Databean<?,?> databean, Object id){
		String autoGeneratedFieldName = fieldInfo.getAutogeneratedFieldName();
		Class<?> primaryKeyClass = fieldInfo.getPrimaryKeySupplier().get().getClass();
		java.lang.reflect.Field autogeneratedField = ReflectionTool.getCachedDeclaredFieldIncludingAncestors(
				primaryKeyClass, autoGeneratedFieldName);
		ReflectionTool.set(autogeneratedField, databean.getKey(), id);
	}

	public static Optional<Field<?>> optFieldToGenerate(DatabeanFieldInfo<?,?,?> fieldInfo, Databean<?,?> databean){
		if(fieldInfo.getAutoGeneratedType().isGenerated()){
			Optional<Field<?>> generatedField = findGeneratedField(databean);
			if(generatedField.isPresent() && generatedField.get().getValue() == null){
				return generatedField;
			}
		}
		return Optional.empty();
	}

	private static Optional<Field<?>> findGeneratedField(Databean<?,?> databean){
		List<Field<?>> fields = databean.getKeyFields();
		for(Field<?> field : fields){
			if(field.getKey().getAutoGeneratedType().isGenerated()){
				return Optional.of(field);
			}
		}
		return Optional.empty();
	}

}
