package gq.baijie.onetab.client.cli;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

import javax.annotation.Nonnull;

import gq.baijie.onetab.ProgressOrResult;
import gq.baijie.onetab.Result;
import gq.baijie.onetab.StorageService;
import gq.baijie.onetab.WebArchive;
import gq.baijie.onetab.internal.storage.BasicStorageService;
import gq.baijie.onetab.internal.storage.StorageModule;

public class Main {

  public static void main(String[] args) {
    final Result<Configuration, Configurations.FromArgumentsFailure> config =
        Configurations.fromArguments(args);
    if (config.failed()) {
      System.out.printf("args error [%s]: %s%n", config.cause().type, config.cause().cause);
      return;
    }

    final InputStream input;
    try {
      input = Files.newInputStream(config.result().importFilePath);
    } catch (IOException e) {
      System.out.println("Cannot open open: " + e.getMessage());
      return;
    }

    final MainComponent component = DaggerMainComponent.builder()
        .storageModule(StorageModule.from(new BasicStorageService(input)))
        .build();

    component.storageService().retrieve(StorageService.TYPE_DEFAULT)
        .filter(ProgressOrResult::isResult)
        .subscribe(result -> {
          if (result.getResult().failed()) {
            result.getResult().cause().printStackTrace();
          } else {
            printResult(result.getResult().result());
          }
        });
  }

  private static void printResult(@Nonnull WebArchive webArchive) {
    if (webArchive.getSections().isEmpty()) {
      return;
    }
    printSection(webArchive.getSections().get(0));
    webArchive.getSections().stream().skip(1).forEach(section -> {
      System.out.println();
      printSection(section);
    });
  }

  private static void printSection(@Nonnull WebArchive.Section section) {
    section.getItems().forEach(item -> {
      if (item.getTitle() != null) {
        System.out.print(item.getLink() + " | ");
        System.out.println(item.getTitle());
      } else {
        System.out.println(item.getLink());
      }
    });
  }

}

@@ -437,17 +437,259 @@
 ss Main 
-%7B
+implements Runnable %7B%0A%0A  final MainComponent component;%0A%0A  public Main(@Nonnull InputStream input) %7B%0A    component = DaggerMainComponent.builder()%0A        .storageModule(StorageModule.from(new BasicStorageService(input)))%0A        .build();%0A  %7D
 %0A%0A  publ
@@ -1219,163 +1219,69 @@
     
-final MainComponent component = DaggerMainComponent.builder
+new Main(input).run
 ()
+;
 %0A  
-      .storageModule(StorageModule.from(new BasicStorageService(input)))%0A        .build();%0A
+%7D%0A%0A  @Override%0A  public void run() %7B
 %0A   

use an instance of Main