package doc.walkthru;

import org.benow.java.annotations.Required;
import org.benow.java.annotations.StringLength;
import org.benow.repository.mapping.JSQLObject;

/**
 * A track, done by a performer
 */
public class TrackImpl extends JSQLObject implements Track {

  private static final long serialVersionUID = 1L;
  
  // @StringLength is a hint for the repository which guides table column construction and makes for nice schema 
  @StringLength(128)
  private String name;
  // @Required ensures that this field is always fetched from the repository whenever this object is.
  @Required
  private Performer performer;
  // duration of the track in seconds
  private int durationInS;

  // repository requires a zero parameter constructor
  protected TrackImpl() {
    super();
  }
  
  public TrackImpl(String title, Performer performer, int durationInS) {
    super();
    this.name = title;
    this.performer=performer;
    this.durationInS=durationInS;
  }
  
  
  public TrackImpl(String title, Performer performer, String timeStr) {
    this(title, performer, parseTimeStr(timeStr));
  }

  private static int parseTimeStr(String timeStr) {
    String times[] = timeStr.split(":");
    int time = 0;
    if (times.length == 3)
      time += Integer.parseInt(times[2]) * 60 * 60;
    if (times.length >= 2)
      time += Integer.parseInt(times[1]) * 60;
    if (times.length > 1)
      time += Integer.parseInt(times[0]);
    else
      throw new NumberFormatException("Expected time in [hh:][mm:]ss format");

    return time;
  }

  @Override
  public int durationInSeconds() {
    return durationInS;
  }

  @Override
  public String getName() {
    return name;
  }

  @Override
  public Performer getPerformer() {
    return performer;
  }

}