/*
 * JBoss, Home of Professional Open Source.
 * See the COPYRIGHT.txt file distributed with this work for information
 * regarding copyright ownership.  Some portions may be licensed
 * to Red Hat, Inc. under one or more contributor license agreements.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * Modified by
 * @author  Data Virtuality GmbH
 * @date    $Date$
 *  
 */
/* EXTENSION
   ISSUE: DVCORE-2441
   FIXED BY: Roman Pedchenko
   DATE: 2014.10.23
   ADOPTED FROM: https://issues.jboss.org/browse/TEIID-247, 2166, 2151, 2234, 2581, 2571, 2369, 1386, 2226, 2233, 2224, 2225, 2257
   EXTENSION*/
// https://issues.jboss.org/browse/TEIID-2181
// https://issues.redhat.com/browse/TEIID-2353
package org.teiid.metadata;

import org.teiid.connector.DataPlugin;
import org.teiid.core.util.StringUtil;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

public class Schema extends AbstractMetadataRecord {

	private static final long serialVersionUID = -5113742472848113008L;

	private boolean physical = true;
	private boolean canCreateViewsProcsFuncs = false;
    private String primaryMetamodelUri = "http://www.metamatrix.com/metamodels/Relational"; //$NON-NLS-1$
    
    protected volatile NavigableMap<String, Table> tables = DVMetadataRecordHolder.initMap(StringUtil.CASE_INSENSITIVE_ORDER);
	private volatile NavigableMap<String, Procedure> procedures = DVMetadataRecordHolder.initMap(StringUtil.CASE_INSENSITIVE_ORDER);
	private volatile NavigableMap<String, FunctionMethod> functions = DVMetadataRecordHolder.initMap(StringUtil.CASE_INSENSITIVE_ORDER);

	private volatile List<AbstractMetadataRecord> resolvingOrder = new CopyOnWriteArrayList<AbstractMetadataRecord>();

	public void addTable(Table table) {
		table.setParent(this);
		if (this.tables.put(table.getName(), table) != null) {
			throw new DuplicateRecordException(DataPlugin.Event.TEIID60013, DataPlugin.Util.gs(DataPlugin.Event.TEIID60013, table.getName()));
		}
		resolvingOrder.add(table);
	}

	public Table removeTable(String tableName) {
		Table previous = this.tables.remove(tableName);
		if (previous != null) {
			resolvingOrder.remove(previous);
		}
		return previous;
	}
	
	public void addProcedure(Procedure procedure) {
		procedure.setParent(this);
		if (this.procedures.put(procedure.getName(), procedure) != null) {
			throw new DuplicateRecordException(DataPlugin.Event.TEIID60014, DataPlugin.Util.gs(DataPlugin.Event.TEIID60014, procedure.getName()));
		}
		resolvingOrder.add(procedure);
	}

	public Procedure removeProcedure(String procedureName) {
		Procedure previous = this.procedures.remove(procedureName);
		if (previous != null) {
			resolvingOrder.remove(previous);
			// remove also all other proc with the same name
			// but different params number and/or types as we can override procedures
			resolvingOrder.stream()
					.filter(e -> e instanceof Procedure && e.getName().equalsIgnoreCase(procedureName))
					.forEach(proc -> resolvingOrder.remove(proc));
		}
		return previous;
	}
	
	public void addFunction(FunctionMethod function) {
		function.setParent(this);
		//TODO: ensure that all uuids are unique
		if (this.functions.put(function.getUUID(), function) != null) {
			throw new DuplicateRecordException(DataPlugin.Event.TEIID60015, DataPlugin.Util.gs(DataPlugin.Event.TEIID60015, function.getUUID()));
		}
		resolvingOrder.add(function);
	}

	public List<FunctionMethod> removeFunctions(String functionNameOrUUID) {
		ArrayList<FunctionMethod> funcs = new ArrayList<>();
		for (FunctionMethod fm : this.functions.values()) {
			if (fm.getName().equalsIgnoreCase(functionNameOrUUID) || fm.getUUID().equals(functionNameOrUUID)) {
				funcs.add(fm);
			}
		}

		for (FunctionMethod func : funcs) {
			FunctionMethod previous = this.functions.remove(func.getUUID());
			if (previous != null) {
				resolvingOrder.remove(previous);
			}
		}
		return funcs;
	}

	/**
	 * Get the tables defined in this schema
	 * @return
	 */
	public NavigableMap<String, Table> getTables() {
		return tables;
	}
	
	public Table getTable(String tableName) {
		return tables.get(tableName);
	}
	
	/**
	 * Get the procedures defined in this schema
	 * @return
	 */
	public NavigableMap<String, Procedure> getProcedures() {
		return procedures;
	}
	
	public Procedure getProcedure(String procName) {
		return procedures.get(procName);
	}
	
	/**
	 * Get the functions defined in this schema in a map of uuid to {@link FunctionMethod}
	 * @return
	 */
	public NavigableMap<String, FunctionMethod> getFunctions() {
		return functions;
	}
	
	/**
	 * Get a funciton by uuid or name
	 * @param funcUuidOrName
	 * @return
	 */
	public FunctionMethod getFunction(String funcUuidOrName) {
		FunctionMethod result = functions.get(funcUuidOrName);
		if (result == null) { // get by name
			for (FunctionMethod fm : this.functions.values()) {
				if (fm.getName().equalsIgnoreCase(funcUuidOrName) || fm.getUUID().equalsIgnoreCase(funcUuidOrName)) {
					result = fm;
				}
			}
		}
		
		return result;
	}	
	
    public String getPrimaryMetamodelUri() {
        return primaryMetamodelUri;
    }

    public boolean isPhysical() {
        return physical;
    }

    public boolean getCanCreateViewsProcsFuncs() {
		return canCreateViewsProcsFuncs;
	}

	/**
     * @param string
     */
    public void setPrimaryMetamodelUri(String string) {
        primaryMetamodelUri = string;
    }

    public void setPhysical(boolean physical) {
		this.physical = physical;
		if (!physical)
			this.canCreateViewsProcsFuncs = true;
	}
    
    public void setCanCreateViewsProcsFuncs(boolean canCreateViewsProcsFuncs) {
		this.canCreateViewsProcsFuncs = canCreateViewsProcsFuncs;
	}

	/**
     * 7.1 schemas did not have functions
     */
    private void readObject(java.io.ObjectInputStream in)
    throws IOException, ClassNotFoundException {
    	in.defaultReadObject();
    	if (this.functions == null) {
    		this.functions = new TreeMap<String, FunctionMethod>(StringUtil.CASE_INSENSITIVE_ORDER);
    	}
	    if (this.resolvingOrder == null) {
		    this.resolvingOrder = new CopyOnWriteArrayList<AbstractMetadataRecord>();
		    this.resolvingOrder.addAll(this.tables.values());
		    this.resolvingOrder.addAll(this.procedures.values());
		    this.resolvingOrder.addAll(this.functions.values());
	    }
    }

	public List<AbstractMetadataRecord> getResolvingOrder() {
		return resolvingOrder;
	}

    public boolean isLazy() {
        return false;
    }
}
