/*******************************************************************************
 * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 * 
 * Contact Info:
 * 	Bruce Donald
 * 	Duke University
 * 	Department of Computer Science
 * 	Levine Science Research Center (LSRC)
 * 	Durham
 * 	NC 27708-0129 
 * 	USA
 * 	brd@cs.duke.edu
 * 
 * Copyright (C) 2011 Jeffrey W. Martin and Bruce R. Donald
 * 
 * <signature of Bruce Donald>, April 2011
 * Bruce Donald, Professor of Computer Science
 ******************************************************************************/


package edu.duke.donaldLab.share.mapping;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import edu.duke.donaldLab.share.nmr.Assignment;
import edu.duke.donaldLab.share.nmr.ChemicalShift;
import edu.duke.donaldLab.share.nmr.DistanceRestraint;
import edu.duke.donaldLab.share.nmr.Rdc;
import edu.duke.donaldLab.share.protein.AminoAcid;
import edu.duke.donaldLab.share.protein.Atom;
import edu.duke.donaldLab.share.protein.AtomAddressInternal;
import edu.duke.donaldLab.share.protein.Protein;
import edu.duke.donaldLab.share.protein.AtomAddressReadable;
import edu.duke.donaldLab.share.protein.Residue;

public class NameMapperProvider
{
	/**************************
	 *   Definitions
	 **************************/
	
	private static final String PathOldToNew = "/resources/atomNameOldToNew.map";
	
	
	/**************************
	 *   Data Members
	 **************************/
	
	private static NameMapperProvider m_instance;
	
	private HashMap<String,HashMap<String,String>> m_maps;
	
	
	/**************************
	 *   Constructors
	 **************************/
	
	private NameMapperProvider( )
	{
		/* Jeff: 12/28/2008 - NOTE:
			There might be a more elegant way to load the map files based on the
			enum values, but loading them explicitly will work just fine.
		*/
		
		m_maps = new HashMap<String,HashMap<String,String>>();
		
		HashMap<String,String> oldToNew = new HashMap<String,String>();
		HashMap<String,String> newToOld = new HashMap<String,String>();
		m_maps.put( getMapKey( NameScheme.Old, NameScheme.New ), oldToNew );
		m_maps.put( getMapKey( NameScheme.New, NameScheme.Old ), newToOld );
		
		try
		{
			// load the old to new map and reverse
			loadMaps( oldToNew, newToOld, PathOldToNew );
		}
		catch( IOException ex )
		{
			System.err.println( "WARNING: cannot load name map!" );
			ex.printStackTrace( System.err );
		}
	}
	
	
	/**************************
	 *   Static Methods
	 **************************/
	
	public static NameMapperProvider getInstance( )
	{
		if( m_instance == null )
		{
			m_instance = new NameMapperProvider();
		}
		
		return m_instance;
	}
	
	
	/**************************
	 *   Methods
	 **************************/
	
	public String mapName( NameScheme source, NameScheme destination, AminoAcid aminoAcid, String atomName )
	{
		String newName = getMap( source, destination ).get( getMapKey( aminoAcid, atomName ) );
		
		if( newName == null )
		{
			newName = atomName;
		}
		
		return newName;
	}
	
	public void mapAtom( NameScheme source, NameScheme destination, Residue residue, Atom atom )
	{
		atom.setName( mapName( source, destination, residue.getAminoAcid(), atom.getName() ) );
	}
	
	public void mapProtein( NameScheme source, NameScheme destination, Protein protein )
	{
		// for each atom in the protein...
		Iterator<AtomAddressInternal> iterAddress = protein.getAtomIndex();
		while( iterAddress.hasNext() )
		{
			AtomAddressInternal address = iterAddress.next();
			Residue residue = protein.getResidue( address );
			Atom atom = protein.getAtom( address );
			
			// map it
			mapAtom( source, destination, residue, atom );
		}
	}
	
	public void mapDistanceRestraints( NameScheme source, NameScheme destination, Protein protein, List<DistanceRestraint<AtomAddressReadable>> restraints )
	{
		// for each noe...
		for( DistanceRestraint<AtomAddressReadable> restraint : restraints )
		{
			for( Assignment<AtomAddressReadable> assignment : restraint )
			{
				mapAddress( source, destination, protein, assignment.getLeft() );
				mapAddress( source, destination, protein, assignment.getRight() );
			}
		}
	}
	
	public void mapAddress( NameScheme source, NameScheme destination, Protein protein, AtomAddressReadable address )
	{
		AtomAddressInternal residueAddress = AddressMapper.mapAddressToResidue( protein, address );
		if( residueAddress == null )
		{
			return;
		}
		Residue residue = protein.getResidue( residueAddress );
		if( residue == null )
		{
			return;
		}
		address.setAtomName( mapName( source, destination, residue.getAminoAcid(), address.getAtomName() ) );
	}
	
	public void mapShifts( NameScheme source, NameScheme destination, Protein protein, List<ChemicalShift> shifts )
	{
		for( ChemicalShift shift : shifts )
		{
			for( AtomAddressReadable address : shift.getAddresses() )
			{
				mapAddress( source, destination, protein, address );
			}
		}
	}
	
	public void mapRdcs( NameScheme source, NameScheme destination, Protein protein, List<Rdc<AtomAddressReadable>> rdcs )
	{
		for( Rdc<AtomAddressReadable> rdc : rdcs )
		{
			mapAddress( source, destination, protein, rdc.getFrom() );
			mapAddress( source, destination, protein, rdc.getTo() );
		}
	}

	public boolean hasMap( NameScheme source, NameScheme destination )
	{
		return m_maps.containsKey( getMapKey( source, destination ) );
	}
	
	
	/**************************
	 *   Functions
	 **************************/
	
	private void loadMaps( HashMap<String,String> forwardMap, HashMap<String,String> reverseMap, String path )
	throws IOException
	{
		// open the resource file
		InputStream in = getClass().getResourceAsStream( path );
		if( in == null )
		{
			return;
		}
		BufferedReader reader = new BufferedReader( new InputStreamReader( in ) );
		
		// read each line...
		String line = null;
		while( ( line = reader.readLine() ) != null )
		{
			// skip blank lines
			line = line.trim();
			if( line.equals( "" ) )
			{
				continue;
			}
			
			// parse the entry
			String[] parts = line.split( ":" );
			AminoAcid aminoAcid = AminoAcid.getByAbbreviation( parts[0] );
			String source = parts[1];
			String destination = parts[2];
			
			// add it to the maps
			forwardMap.put( getMapKey( aminoAcid, source ), destination );
			reverseMap.put( getMapKey( aminoAcid, destination ), source );
		}
	}
	
	private HashMap<String,String> getMap( NameScheme source, NameScheme destination )
	{
		return m_maps.get( getMapKey( source, destination ) );
	}
	
	private String getMapKey( NameScheme source, NameScheme destination )
	{
		return source + "_" + destination;
	}
	
	private String getMapKey( AminoAcid aminoAcid, String atomName )
	{
		return aminoAcid.getCode() + "_" + atomName.toUpperCase();
	}
}
