/* (non-Javadoc)
   * @see ca.cmput301f13t03.adventure_datetime.model.IWebStorage#publishStory(ca.cmput301f13t03.adventure_datetime.model.Story, java.util.List)
   */
  @Override
  public boolean publishStory(Story story, List<StoryFragment> fragments) throws Exception {
    boolean succeeded;

    // I am not cleaning up old fragments because I am assuming we do not support
    // deleting fragments. If we do support that, then I will have to clean them up.
    Index index =
        new Index.Builder(story).index(_index).type("story").id(story.getId().toString()).build();
    JestResult result = execute(index);
    succeeded = result.isSucceeded();

    if (story.getThumbnail() != null) {
      succeeded &= putImage(story.getThumbnail());
    }

    Bulk.Builder bulkBuilder = new Bulk.Builder().defaultIndex(_index).defaultType("fragment");

    if (fragments != null) {
      for (StoryFragment f : fragments) {
        f.updateMediaIds();
        bulkBuilder.addAction(new Index.Builder(f).id(f.getFragmentID().toString()).build());
      }

      result = execute(bulkBuilder.build());
      succeeded &= result.isSucceeded();

      for (StoryFragment f : fragments) {
        succeeded &= putImages(f.getStoryMedia());
      }
    }

    return succeeded;
  }
  /* (non-Javadoc)
   * @see ca.cmput301f13t03.adventure_datetime.model.IWebStorage#getStory(java.util.UUID)
   */
  @Override
  public Story getStory(UUID storyId) throws Exception {
    Get get = new Get.Builder(_index, storyId.toString()).type("story").build();
    JestResult result = execute(get);
    Story story = result.getSourceAsObject(Story.class);

    Image image = getImage(storyId);
    if (image != null) story.setThumbnail(image.getEncodedBitmap());

    return story;
  }
  private void mapImagesToStories(List<Story> stories) throws Exception {
    if (stories == null || stories.size() == 0) return;

    // Get the thumbnails
    List<UUID> ids = new ArrayList<UUID>();
    for (Story s : stories) {
      ids.add(s.getId());
    }

    List<Image> images = getImages(ids);

    for (Image i : images) {
      for (Story s : stories) {
        if (s.getId().equals(i.getId())) {
          s.setThumbnail(i.getEncodedBitmap());
          break;
        }
      }
    }
  }