/* (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;
  }
  private boolean putImages(List<Image> images) throws Exception {
    if (images == null) return true;

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

    for (Image i : images) {
      bulkBuilder.addAction(new Index.Builder(i).id(i.getId().toString()).build());
    }

    JestResult result = execute(bulkBuilder.build());
    return result.isSucceeded();
  }
 @Override
 public boolean send(Index index) {
   if (messageCounter >= flushLimit) {
     flush();
   }
   bulk = bulk.addAction(index);
   messageCounter++;
   return true;
 }
 @Override
 public void flush() {
   logger.debug("Flushing messages for ES destination [mode=http]");
   Bulk bulkActions = bulk.build();
   try {
     client.getClient().execute(bulkActions);
   } catch (IOException e) {
     logger.error(e.getMessage());
   }
   bulk = new Bulk.Builder();
   messageCounter = 0;
 }