package org.lodder.subtools.multisubdownloader.workers;

import java.util.ArrayList;
import java.util.List;
import org.lodder.subtools.multisubdownloader.subtitleproviders.SubtitleProvider;
import org.lodder.subtools.sublibrary.logging.Logger;
import org.lodder.subtools.sublibrary.model.Release;
import org.lodder.subtools.sublibrary.model.Subtitle;

public class SearchWorker extends Thread {

  protected final SubtitleProvider provider;
  private final SearchManager scheduler;
  private boolean busy = false;
  private boolean isInterrupted = false;

  public SearchWorker(SubtitleProvider provider, SearchManager scheduler) {
    this.provider = provider;
    this.scheduler = scheduler;
  }

  @Override
  public void run() {
    String language = this.scheduler.getLanguage();
    this.busy = false;
    while (!this.isInterrupted()) {
      this.busy = true;
      Release release = this.scheduler.getNextRelease(provider.getName());
      if (release == null) {
        this.busy = false;
        break;
      }
      Logger.instance.debug("[Search] " + this.provider.getName() + " searching " + release.toString());

      List<Subtitle> subtitles = this.provider.search(release, language);
      if (subtitles == null) {
        subtitles = new ArrayList<>();
      }

      /* clone to prevent other threads from ever messing with it */
      subtitles = new ArrayList<>(subtitles);

      this.busy = false;
      Logger.instance.debug("[Search] " + this.provider.getName() + " found " + subtitles.size() + " subtitles for " + release.toString());

      if (!this.isInterrupted()) {
        this.scheduler.onCompleted(release, subtitles);
      }
    }
  }

  @Override
  public boolean isInterrupted() {
    /* bugfix? interupt-state isn't being held */
    return super.isInterrupted() || this.isInterrupted;
  }

  @Override
  public void interrupt() {
    this.isInterrupted = true;
    super.interrupt();
  }

  public boolean isBusy() {
    return busy;
  }
}

@@ -547,16 +547,79 @@
 = false;
+%0A  private Release release;%0A  private List%3CSubtitle%3E subtitles;
 %0A%0A  publ
@@ -986,26 +986,16 @@
 provider
-.getName()
 );%0A     
@@ -1064,24 +1064,54 @@
 ak;%0A      %7D%0A
+      this.release = release;%0A
       Logger
@@ -1428,24 +1428,29 @@
 it */%0A      
+this.
 subtitles = 
@@ -1523,32 +1523,41 @@
 .instance.debug(
+%0A        
 %22%5BSearch%5D %22 + th
@@ -1628,16 +1628,26 @@
 es for %22
+%0A         
  + relea
@@ -1737,25 +1737,11 @@
 ted(
-release, subtitle
+thi
 s);%0A
@@ -2064,11 +2064,204 @@
 usy;%0A  %7D
+%0A%0A  public Release getRelease() %7B%0A    return release;%0A  %7D%0A%0A  public List%3CSubtitle%3E getSubtitles() %7B%0A    return subtitles;%0A  %7D%0A%0A  public SubtitleProvider getProvider() %7B%0A    return provider;%0A  %7D
 %0A%7D%0A

Refactor SearchWorker