package eu.hsrw.ias.ggd;

import java.util.Date;
import java.util.HashMap;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;

// Create a class extends with TimerTask
public class ScheduledTask extends TimerTask {

  Date now; // to display current time

  // Add your task here
  public void run() {
    // Display current time
    now = new Date(); // initialize date
    System.out.println("Time is :" + now);

    try {
      Greenhouse greenhouse = ApiCall.FetchDataFromApi();

      System.out.println(
        "Final Size " +
        greenhouse.getDevices().size() +
        " Devices: " +
        greenhouse.getDevices()
      );

      KieServices ks = KieServices.Factory.get();
      KieContainer kContainer = ks.getKieClasspathContainer();
      //Get the session named kseesion-rule that we defined in kmodule.xml above.
      //Also by default the session returned is always stateful.
      KieSession kSession = kContainer.newKieSession("ksession-rule");

      FactHandle g = kSession.insert(greenhouse);
      kSession.insert(g);

      //            FactHandle x = kSession.insert(Severity.Unknown);
      //            kSession.insert(x);

      for (Device d : greenhouse.getDevices()) {
        FactHandle f = kSession.insert(d);
        kSession.insert(f);
      }
      //FactHandle fact1;
      //fact1 = kSession.insert(outputDevices);
      //            System.out.println(fact1);
      //            kSession.insert(fact1);
      kSession.fireAllRules();
    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (ExecutionException e) {
      e.printStackTrace();
    } catch (TimeoutException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
