/*
 * Copyright 2010 Lari Natri <lari.natri@gmail.com>
 *
 *  This program 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.
 * 
 *  This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package compid.report.protgroup;

import compid.data.tuples.DatasetInfo.AlgType;
import compid.data.tuples.PeptideHit;
import compid.sequences.AminoSequence;
import java.io.Serializable;

/**
 * Represents a peptide. This class is immutable and as such, thread-safe.
 * Natural ordering provided by the implementation of Comparable compares
 * the peptide hit scores (which are non-comparable for different source
 * software).
 * 
 * @author Lari Natri
 */
public final class ProtGroupQuery implements Comparable<ProtGroupQuery>,
        Serializable
{

    private static final long serialVersionUID = 54321L;
    
    private final AminoSequence seq; // Peptide's sequence
    private final double origScore;  // Score originating in Mascot/Paragon
    private final AlgType algorithm; // Originating algorithm (software)
    private final String scan;       // Scan title

    private final int preCalcHash;   // Hash code calculated only once

    /**
     * Constructor.
     * @param sequence Amino Acid sequence, can not be null
     * @param origScore Original peptide hit origScore given by Mascot/Paragon
     * @param scanTitle Scan title, null value is converted to an empty string
     * @throws IllegalArgumentException Thrown if sequence is empty
     */
    public ProtGroupQuery(final AminoSequence sequence, final double score,
                            final AlgType algorithm, final String scanTitle)
                            throws IllegalArgumentException {
        if (sequence.getLength()==0) {
            throw new IllegalArgumentException("Peptide must have a " +
                    "non-empty sequence");
        }
        this.seq = sequence;
        this.origScore = score;
        this.algorithm = algorithm;
        this.scan = scanTitle==null ? "" : scanTitle;

        this.preCalcHash = this.preCalculateHashCode();
    }

    /**
     * Constructor.
     * @param sequence Amino Acid sequence, can not be null
     * @param origScore Original peptide hit origScore given by Mascot/Paragon
     * @param scanTitle Scan title, null value is converted to an empty string
     * @throws IllegalArgumentException Thrown if sequence is empty
     */
    public ProtGroupQuery(final String sequence, final double score,
                            final AlgType algorithm, final String scanTitle)
                            throws IllegalArgumentException {
        this(new AminoSequence(sequence),score,algorithm,scanTitle);
    }

    /**
     * Returns the amino acid sequence of this peptide.
     * @return Sequence, guaranteed to be non-empty
     */
    public final AminoSequence getSequence() {
        return this.seq;
    }

    /**
     * Returns the original match score given by source software for this
     * peptide. Note that these scores are non-comparable if originating
     * in different software.
     * @return origScore
     */
    public final double getScore() {
        return this.origScore;
    }

    /**
     * Returns the peptide confidence score in a comparable form. See
     * PeptideHit.getComparableConfidence().
     * @return peptide confidence [0..1] or -1 if unable to compute
     */
    public final double getComparableScore() {
        return PeptideHit.getComparableConfidence(this.origScore,
                                                  this.algorithm);
    }

    /**
     * Returns the source software algorithm type
     * @return source software algorithm
     */
    public final AlgType getAlgorithm() {
        return this.algorithm;
    }

    /**
     * Returns the title for the scan resulting in this peptide hit.
     * @return scan title, guaranteed to be non-null
     */
    public final String getScanTitle() {
        return this.scan;
    }

    @Override
    public final boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final ProtGroupQuery other = (ProtGroupQuery) obj;
        if (this.seq != other.seq && (this.seq == null || !this.seq.equals(other.seq))) {
            return false;
        }
        if (this.origScore != other.origScore) {
            return false;
        }
        if ((this.scan == null) ? (other.scan != null) : !this.scan.equals(other.scan)) {
            return false;
        }
        return true;
    }

    @Override
    public final int hashCode() {
        return this.preCalcHash;
    }

    /**
     * Implements Comparable interface. This compares the scores of peptide
     * hits using the comparable score. See PeptideHit.getComparableScore().
     * Note: this class has a natural ordering that is inconsistent with equals.
     * @param o the object to be compared
     * @return a negative integer, zero, or a positive integer as this object
     *         is less than, equal to, or greater than the specified object
     */
    @Override
    public final int compareTo(ProtGroupQuery o) {
        if (this==o || this.equals(o)) {
            return 0;
        }
        if (this.getComparableScore()<o.getComparableScore()) {
            return -2;
        } else if (this.getComparableScore()>o.getComparableScore()) {
            return 2;
        } else { // peps have same score, but order must be established!
            int hashDifference = this.hashCode()-o.hashCode();
            if (hashDifference==0) { // last resort
                System.out.println("DEBUG: ProtGroupPeptide comparator " +
                        "returned an inconsistent result");
                return 1;
            } else {
                return hashDifference;
            }
        }
    }


    /**
     * Calculates and returns the hash code. Meant to be called only once as
     * the last sentence in the constructor. hashCode() will return the value
     * calculated by this function and saved in the constructor.
     * @return hash code
     */
    private final int preCalculateHashCode() {
        int hash = 7;
        hash = 41 * hash + (this.seq != null ? this.seq.hashCode() : 0);
        hash = 41 * hash + (int) (Double.doubleToLongBits(this.origScore) ^ (Double.doubleToLongBits(this.origScore) >>> 32));
        hash = 41 * hash + (this.algorithm != null ? this.algorithm.hashCode() : 0);
        hash = 41 * hash + (this.scan != null ? this.scan.hashCode() : 0);
        return hash;
    }

}
