package com.peterjosling.scroball;

import android.media.MediaMetadata;

import com.google.common.base.Optional;
import com.peterjosling.scroball.transforms.TitleExtractor;

import org.immutables.value.Value;

@Value.Immutable
public abstract class Track {

  public abstract String track();
  public abstract String artist();
  public abstract Optional<String> album();
  public abstract Optional<String> albumArtist();
  @Value.Auxiliary
  public abstract Optional<Long> duration();

  public boolean isValid() {
    return !track().equals("") && !artist().equals("");
  }

  public static Track fromMediaMetadata(MediaMetadata metadata) {
    String title = metadata.getString(MediaMetadata.METADATA_KEY_TITLE);
    String artist = metadata.getString(MediaMetadata.METADATA_KEY_ARTIST);
    String album = metadata.getString(MediaMetadata.METADATA_KEY_ALBUM);
    String albumArtist = metadata.getString(MediaMetadata.METADATA_KEY_ALBUM_ARTIST);
    long duration = metadata.getLong(MediaMetadata.METADATA_KEY_DURATION);

    if (title == null) {
      title = metadata.getString(MediaMetadata.METADATA_KEY_DISPLAY_TITLE);

      if (title  == null) {
        title = "";
      }
    }

    ImmutableTrack.Builder builder = ImmutableTrack.builder()
        .track(title)
        .artist(artist)
        .album(Optional.fromNullable(album))
        .albumArtist(Optional.fromNullable(albumArtist));

    if (duration > 0) {
      builder.duration(duration);
    }

    if (artist == null) {
      new TitleExtractor().transform(builder.build());
    }
    return builder.build();
  }

  @Value.Lazy
  public static Track empty() {
    return ImmutableTrack.builder().track("").artist("").build();
  }
}

@@ -29,16 +29,48 @@
 oball;%0A%0A
+import android.graphics.Bitmap;%0A
 import a
@@ -97,16 +97,16 @@
 tadata;%0A
-
 %0Aimport 
@@ -464,18 +464,16 @@
 uxiliary
-%0A 
  public 
@@ -507,16 +507,75 @@
 ation();
+%0A  @Value.Auxiliary public abstract Optional%3CBitmap%3E art();
 %0A%0A  publ
@@ -1027,24 +1027,93 @@
 UM_ARTIST);%0A
+    Bitmap art = metadata.getBitmap(MediaMetadata.METADATA_KEY_ART);%0A
     long dur
@@ -1337,24 +1337,124 @@
    %7D%0A    %7D%0A%0A
+    if (art == null) %7B%0A      art = metadata.getBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART);%0A    %7D%0A%0A
     Immutabl
@@ -1594,16 +1594,16 @@
 album))%0A
-
         
@@ -1650,16 +1650,57 @@
 Artist))
+%0A        .art(Optional.fromNullable(art))
 ;%0A%0A    i

Store optional artwork bitmap in Track