/**
 * Represent my CD Collection with CDs
 * Author : skotthe
 */
public class CDCollection{

  private CD[] theCollection;

  // Constructor
  CDCollection(int collectionSize){
    this.theCollection = new CD[collectionSize];
  }

  //Accesors
  //Setter
  public void setTheCollection(CD[] newCollection){
    theCollection = newCollection;
  }

  //getter
  public CD[] getTheCollection(){
    return theCollection;
  }


  public void showInfo(){
    //pretty print each CD in turn 
    System.out.println(" #### The Collection ####");
    for (int i = 0; i < theCollection.length && theCollection[i] !=null;i++){
      System.out.println(" CD "+ i+" :");
      theCollection[i].showInfo();
    }
    System.out.println("\t\t\t\t #### The Collection ####");
  }


  public boolean addCD(CD newCD){
    // pre: a CD
    // post: True on success, false otherwise
    //  DO not allow duplicate cds 
    if (!hasDuplicates(newCD)){
      return addThisCD(newCD);
    }else{
      return false;
    }
  }

  private boolean addThisCD(CD aCD){
    // pre: aCD that is not already in the collection 
    // post: True if addition was succesful, false otherwise
    int i = 0; 
    for(;i < theCollection.length && theCollection[i]!=null;i++){
      ;
    }
    if (i < theCollection.length){
      theCollection[i] = aCD;
      return true;
    }else{
      return false;
    }
  }

  private boolean hasDuplicates(CD aCD){
    //pre: aCD 
    //post: True if aCD is exactly the same as a CD in the collection 
    //      False otherwise.
      for (int i =0; i < theCollection.length && theCollection[i]!=null;i++){
      if (sameCD(theCollection[i],aCD)){
        return true;
      }
    }
    return false;
  }

  private boolean sameCD(CD first, CD second){
    //pre: two CDs
    //post: True if exactly the same i.e., same :
    //              title, artist, year, number of songs,
    //              order of songs, title of each song is the same, 
    boolean titles = first.getTitle().equalsIgnoreCase(second.getTitle());
    boolean artists = first.getArtist().equalsIgnoreCase(second.getArtist());
    boolean releases = first.getReleaseYear() == second.getReleaseYear();
    boolean duplicateSongs = hasIdenticalSongs(first,second);

    return (titles && artists && releases && duplicateSongs);
  }
        
  private boolean hasIdenticalSongs(CD one, CD two){
    //pre: two CDs (check if they are identical)
    //post: TRUE : if duplicate songs exists
    //      FALSE: otherwise
    String[] oneSongs = one.getSongTitles();
    String[] twoSongs = two.getSongTitles();
    if (oneSongs.length != twoSongs.length){
      return false;
    } else {
      for (int i = 0; i < oneSongs.length; i++){
        if (!two.hasDuplicates(oneSongs[i])){
          return false;
        }
      }
      return true;
    }
  }
}

