/**
 * 
 * Written by Márton Münz and Philip C Biggin
 * Copyright (c) University of Oxford, United Kingdom
 * Visit http://sbcb.bioch.ox.ac.uk/jgromacs/
 * 
 * This source code file is part of JGromacs v1.0.
 * 
 * JGromacs v1.0 is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * JGromacs v1.0. 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with JGromacs v1.0. If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package jgromacs.data;
import java.util.ArrayList;

/**
 * Objects of this class represent a single trajectory
 *
 */
public class Trajectory implements Cloneable {

	private Structure structure = new Structure();
	private ArrayList<PointList> frames = new ArrayList<PointList>();
	private String name = "Noname";
	private double startTime = 0;
	private double timeStep = 0;

	// Constructors
	
	/**
	 * Constructs a new Trajectory object
	 *
	 * 
	 */
	public Trajectory() {
		
	}
	
	/**
	 * Constructs a new Trajectory object of given name
	 *
	 * 
	 */
	public Trajectory(String name) {
		super();
		this.name = name;
	}

	/**
	 * Constructs a new Trajectory object of given structure
	 *
	 * 
	 */
	public Trajectory(Structure structure){
		this.structure = structure;
	}
		
	/**
	 * Constructs a new Trajectory object made from an ensemble of structures
	 *
	 * 
	 */
	public Trajectory(Structure[] ensemble){
		structure = ensemble[0];
		for (int i = 0; i < ensemble.length; i++) {
			Structure s = ensemble[i];
			frames.add(s.getAllAtomCoordinates());
		}
	}
	
	// Getters and setters
	
	/**
	 * Returns frames of the trajectory as an ArrayList object
	 * @return frames as an ArrayList
	 * 
	 */
	public ArrayList<PointList> getFrames(){
		return frames;
	}
	
	/**
	 * Returns frame #i of the trajectory as a PointList object
	 * @return frame #i as a PointList
	 * 
	 */
	public PointList getFrameAsPointList(int i){
		return frames.get(i);
	}
	
	/**
	 * Returns frame #i of the trajectory as a Structure object
	 * @return frame #i as a Structure
	 * 
	 */
	public Structure getFrameAsStructure(int i){
		Structure ret = (Structure)structure.clone();
		ret.setName("Frame:"+i);
		PointList pointlist = getFrameAsPointList(i);
		ret.setAllAtomCoordinates(pointlist);
		return ret;
	}
	
	/**
	 * Returns the number of frames in the trajectory
	 * @return number of frames
	 * 
	 */
	public int getNumberOfFrames(){
		return frames.size();
	}
	
	/**
	 * Returns the name of trajectory
	 * @return name of trajectory
	 * 
	 */
	public String getName() {
		return name;
	}
	
	/**
	 * Sets the name of trajectory
	 * @param name name of trajectory
	 * 
	 */
	public void setName(String name) {
		this.name = name;
	}
	
	/**
	 * Returns the start time of trajectory
	 * @return start time of trajectory
	 * 
	 */
	public double getStartTime() {
		return startTime;
	}

	/**
	 * Sets the start time of trajectory
	 * @param startTime start time of trajectory
	 * 
	 */
	public void setStartTime(double startTime) {
		this.startTime = startTime;
	}

	/**
	 * Returns the time step of trajectory
	 * @return time step of trajectory
	 * 
	 */
	public double getTimeStep() {
		return timeStep;
	}

	/**
	 * Sets the time step of trajectory
	 * @param timeStep time step of trajectory
	 * 
	 */
	public void setTimeStep(double timeStep) {
		this.timeStep = timeStep;
	}
	
	/**
	 * Sets the structure described by the trajectory
	 * @param structure structure described by the trajectory
	 * 
	 */
	public void setStructure(Structure structure) {
		this.structure = structure;
	}
	
	/**
	 * Returns the mean frame of trajectory
	 * @return mean frame
	 * 
	 */
	public PointList getMeanFrame(){
		double counter = 0;
		PointList ret = new PointList();
		int numofpoints = getFrameAsPointList(0).getNumberOfPoints();
		for (int i = 0; i < numofpoints; i++) ret.addPoint(new Point3D(0,0,0));
		for (int i = 0; i < getNumberOfFrames(); i++) {
			PointList frame = getFrameAsPointList(i);
			for (int j = 0; j < numofpoints; j++)
				ret.setPoint(j,ret.getPoint(j).plus(frame.getPoint(j)));
			counter++;
		}
		for (int j = 0; j < numofpoints; j++) 
			ret.setPoint(j, ret.getPoint(j).multiplyByScalar(1.0/counter));
						
		return ret;
	}

	/**
	 * Returns the number of atoms in the trajectory
	 * @return number of atoms 
	 * 
	 */
	public int getNumberOfAtoms(){
	 return getFirstFrameAsPointList().getNumberOfPoints();
	}
	
	/**
	 * Returns the number of residues in the trajectory
	 * @return number of residues 
	 * 
	 */
	public int getNumberOfResidues(){
	 return structure.getNumberOfResidues();
	}
	
	/**
	 * Returns the initial frame of trajectory as a PointList
	 * @return initial frame 
	 * 
	 */
	public PointList getFirstFrameAsPointList(){
		return frames.get(0);
	}
	
	/**
	 * Returns the initial frame of trajectory as a Structure
	 * @return initial frame 
	 * 
	 */
	public Structure getFirstFrameAsStructure(){
		return getFrameAsStructure(0);
	}
	
	/**
	 * Returns the last frame of trajectory as a PointList
	 * @return last frame 
	 * 
	 */
	public PointList getLastFrameAsPointList(){
		return getFrameAsPointList(getNumberOfFrames()-1);
	}
	
	/**
	 * Returns the last frame of trajectory as a Structure
	 * @return last frame 
	 * 
	 */
	public Structure getLastFrameAsStructure(){
		return getFrameAsStructure(getNumberOfFrames()-1);
	}
	
	
	// Modifications
	
	/**
	 * Adds a new frame to the trajectory
	 * @param frame new frame
	 * 
	 */
	public void addFrame(PointList frame){
		frames.add(frame);
	}
	
	/**
	 * Removes frame #i from the trajectory
	 * 
	 */
	public void removeFrame(int i){
		frames.remove(i);
	}

	/**
	 * Replaces frame #i with a new frame
	 * @param frame new frame
	 * 
	 */
	public void setFrame(int i, PointList frame){
		frames.set(i, frame);
	}
	
	// Conversion
		
	/**
	 * Converts frame index to simulation time
	 * @param frameindex frame index
	 * @return simulation time
	 */
	public double convertFrameIndexToTime(int frameindex){
		return startTime+frameindex*timeStep;
	}
	
	/**
	 * Converts simulation time to frame index
	 * @param time simulation time
	 * @return frame index
	 */
	public int convertTimeToFrameIndex(double time){
		
		return (int) Math.round((time-startTime)/timeStep);
	}
		
	// Getting subtrajectories
	
	/**
	 * Returns the subtrajectory between the given start and end frames
	 * @param startframe start frame
	 * @param endframe end frame
	 * @return subtrajectory
	 */
	public Trajectory getSubTrajectory(int startframe, int endframe){
		Trajectory ret = new Trajectory(structure);
		ret.setName("Subtrajectory["+startframe+","+endframe+"](from:"+getName()+")");
		ret.timeStep = timeStep;
		ret.startTime = convertFrameIndexToTime(startframe);
		for (int i = startframe; i < endframe+1; i++) {
			ret.addFrame((PointList)getFrameAsPointList(i).clone());
		}
		return ret;
	}
	
	/**
	 * Returns the subtrajectory between the given start and end frames using the given sampling frequency 
	 * @param startframe start frame
	 * @param endframe end frame
	 * @param frequency sampling frequency
	 * @return subtrajectory
	 */
	public Trajectory getSubTrajectory(int startframe, int endframe, int frequency){
		Trajectory ret = new Trajectory(structure);
		ret.setName("Subtrajectory["+startframe+","+endframe+"][freq:"+frequency+"](from:"+getName()+")");
		ret.timeStep = timeStep*frequency;
		ret.startTime = convertFrameIndexToTime(startframe);
		for (int i = startframe; i < endframe+1; i++) {
			if ((i-startframe)%frequency==0) ret.addFrame((PointList)getFrameAsPointList(i).clone());
		}
		return ret;
	}
	
	/**
	 * Returns the subtrajectory defined by the given index set
	 * @param indices index set of subtrajectory
	 * @return subtrajectory
	 */
	public Trajectory getSubTrajectory(IndexSet indices){
		Structure s = structure.getSubStructure(indices);
		Trajectory ret = new Trajectory(s);
		ret.setName("Subtrajectory[atoms:"+indices.getName()+"](from:"+getName()+")");
		ArrayList<Integer> listIndices = structure.convertIndicesToArrayListIndices(indices);
		for (int i = 0; i < getNumberOfFrames(); i++) {
			PointList frame = getFrameAsPointList(i);
			ret.addFrame(frame.getSubList(listIndices));
		}
		ret.setStartTime(startTime);
		ret.setTimeStep(timeStep);
		return ret;
	}
	
	
	/**
	 * Returns the subtrajectory defined by the given frame list
	 * @param framelist frame list
	 * @return subtrajectory
	 */
	public Trajectory getSubTrajectory(FrameIndexSet framelist){
		Trajectory ret = new Trajectory(structure);
		ret.setName("Subtrajectory[frames:"+framelist.getName()+"](from:"+getName()+")");	
		ret.timeStep = 0;
		ret.startTime = 0;
		for (int i = 0; i < getNumberOfFrames(); i++) {
			if (framelist.isFrameIn(i))
			ret.addFrame((PointList)getFrameAsPointList(i).clone());
		}
		return ret;
	}
	
	// toString, clone, equals
	
	/**
	 * Returns the String representation of trajectory
	 *
	 * @return String representation
	 */
	public String toString(){
		if (getNumberOfFrames()>0)
		return "Name: "+name+" | Start time: "+startTime+" | Time step: "+timeStep+" | ("+getNumberOfAtoms()+" atoms, "+getNumberOfFrames()+" frames)";
		else return "Name: "+name+" | Start time: "+0.0+" | Time step: "+0.0+" | (0 atoms, 0 frames)";
	}
	
	/**
	 * Returns true if the two trajectories are identical
	 * @param other the other trajectory
	 * 
	 */
	public boolean equals(Object other){
		if (other == null) return false;
		if (other == this) return true;
		if (this.getClass() != other.getClass()) return false;
		Trajectory t = (Trajectory)other;
		if (!t.name.equals(name)) return false;
		if (Math.abs(t.startTime-startTime)>0.0000001) return false;
		if (Math.abs(t.timeStep-timeStep)>0.0000001) return false;
		if (!t.structure.equals(structure)) return false;
		if (t.getNumberOfFrames()!=getNumberOfFrames()) return false;
		for (int i = 0; i < getNumberOfFrames(); i++) {
			if (!t.getFrameAsPointList(i).equals(getFrameAsPointList(i)))
				return false;
		}
		return true;
	}
	
	/**
	 * Returns hash code
	 * 
	 */
	public int hashCode() {
		return frames.size()+name.length()+structure.getNumberOfResidues();
	}
	
	
	/**
	 * Returns an identical Trajectory object 
	 *
	 * @return clone of the trajectory
	 */
	public Object clone(){
		try {
			Trajectory ret = (Trajectory)super.clone();
			ret.name = name;
			ret.startTime = startTime;
			ret.timeStep = timeStep;
			ret.structure = (Structure)structure.clone();
			ret.frames = new ArrayList<PointList>();
			for (int i = 0; i < getNumberOfFrames(); i++) 
			ret.addFrame((PointList)getFrameAsPointList(i).clone());
			return ret;
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
			return null;
		}
		
	}
	
}
