package org.hogel.command.job;

import com.google.inject.Inject;
import org.hogel.bookscan.BookscanClient;
import org.hogel.bookscan.OptimizeOption;
import org.hogel.bookscan.model.Book;
import org.hogel.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class OptimizeAllJob extends AbstractJob {
    private static final Logger LOG = LoggerFactory.getLogger(OptimizeAllJob.class);

    @Inject
    Config config;

    @Inject
    BookscanClient bookscanClient;

    @Override
    public void run() throws Exception {
        List<Book> books = bookscanClient
            .fetchBooks()
            .timeout(config.getTimeout())
            .get();

        // TODO: load optimize option from config file
        OptimizeOption option = new OptimizeOption();
        option.addFlag(OptimizeOption.Flag.COVER);
        option.addFlag(OptimizeOption.Flag.BOLD);
        option.addFlag(OptimizeOption.Flag.WHITE);

        option.addType(OptimizeOption.Type.KINDLEP);

        long wait = config.getWait();

        for (Book book : books) {
            LOG.info("Optimize: {}", book.getFilename());
            bookscanClient
                .requestBookOptimize(book, option)
                .timeout(config.getTimeout())
                .get();
            Thread.sleep(wait);
        }
    }
}

@@ -142,16 +142,71 @@
 Option;%0A
+import org.hogel.bookscan.exception.BookscanException;%0A
 import o
@@ -235,16 +235,16 @@
 l.Book;%0A
-
 import o
@@ -481,24 +481,81 @@
 ob.class);%0A%0A
+    private static final int PARALLEL_TUNING_COUNT = 5;%0A%0A
     @Inject%0A
@@ -1197,16 +1197,206 @@
 ooks) %7B%0A
+            while (countOptimizingBooks() %3E PARALLEL_TUNING_COUNT) %7B%0A                LOG.info(%22waiting optimizing...%22, book.getFilename());%0A                Thread.sleep(wait);%0A            %7D%0A
         
@@ -1589,24 +1589,24 @@
     .get();%0A
-
             
@@ -1640,11 +1640,287 @@
  %7D%0A    %7D
+%0A%0A    private int countOptimizingBooks() %7B%0A        try %7B%0A            return bookscanClient.fetchOptimizingBooks().timeout(config.getTimeout()).get().size();%0A        %7D catch (BookscanException e) %7B%0A            LOG.error(e.getMessage(), e);%0A            return 0;%0A        %7D%0A    %7D
 %0A%7D%0A

Add optimize waiting