import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

/*
 * Retrieves system parameters at a predefined interval
 */
public class SystemProfiler
{
  public LlamaAdaptive algo = new LlamaAdaptive();

  public WindowsSystemParameters sysparams = new WindowsSystemParameters();

  public PodcastTask app = new PodcastTask();

  FileHandler filehandler = new FileHandler();

  ClientServerSync csync = new ClientServerSync();

  public static String old_date = "null";

  public static String new_date = "null";

  public static int file_count = 0;
  
  public SystemProfiler (int SleepInterval)
  {
    this.setSleepInterval(SleepInterval);
  }

  // Checks OS type and runs the timer to request for parameters at a specified
  // interval
  public void getSystemProfile ()
      throws InterruptedException, FileNotFoundException, IOException
  {
    boolean learned = false;

    long delay = 0;
    long period = 10000;

    Timer timer = new Timer();
    // Schedules the specified task for repeated fixed-delay execution,
    // beginning after the specified delay
    timer.schedule(new ClientTimerTask(), delay, period);

    LearningTool learn = new LearningTool();

    SystemParametersBean params = sysparams.Scheduler();

    boolean filepresent = learnedearlier(PropertyFileValues.appenergyinfo);
    System.out.println("filepresent " + filepresent);
    
    if (filepresent)
    {
      learned = true;
    }
    // 0 means not charging
    else if (new Integer(String.valueOf(params.getAc())).intValue() == 0)
    {
      System.out.println("appenergyinfo not present, so learn energypattern");
      learn.learnenergypattern();
    }

    // set up a time to check for whether you plugged in
    ClientServerSync sync = new ClientServerSync();

    while (true)
    {
      // do the
      boolean charging = false;
      params = sysparams.Scheduler();

      File dir = new File(PropertyFileValues.destination_dir);
      String[] file_list = dir.list();
      System.out.println("file_list length " + file_list.length);

      // uploading a file to the server
      if (file_list.length > 1)
      {
        String filename =
            "Logger_" + String.valueOf(params.getDate()).substring(0,10);

        for (int i = 0; i < file_list.length; i++)
        {
          String filetobesend = file_list[i];

          if (filetobesend.compareTo(filename) != 0)
          {
            System.out.println("Mac address "
                + String.valueOf(params.getMACAddress()));

            String retval =
                sync.connect(String.valueOf(params.getMACAddress()),
                    filetobesend);

            if (retval.compareTo("success") == 0)
            {
              System.out.println("File Send  " + file_list[i]);
              FileHandler.moveFileToArchive(filetobesend);
            }
          }
        }
      }

      rechargeinfo time = new rechargeinfo();
      // 1 means charging
      if (new Integer(String.valueOf(params.getAc())).intValue() == 1)
      {
        System.out.println("Charging");
        charging = true;
      }

      time.dotask = false;

      if (learned == true && !charging)
      {
        System.out.println("running algorithm");
        time = algo.runalgorithm(params,charging);
      }
      else if (charging == true)
      {
        System.out.println("charging is true so runalgorithm");
        time = algo.runalgorithm(params,charging);
      }

      if (time.dotask)
      {
        app.runapplication(time.sizegroup, PropertyFileValues.sleepinterval);
      }

      if (learned == false)
      {
        if (new Integer(String.valueOf(params.getAc())).intValue() == 0)
        {
          System.out.println("learned == false");
          learn.learnenergypattern();
        }
      }

      filepresent = learnedearlier(PropertyFileValues.appenergyinfo);

      if (filepresent)
      {
        learned = true;
      }
    }
  }

  private boolean learnedearlier (String fname)
  {
    try
    {
      FileReader f = new FileReader(new File(fname));
      BufferedReader fr = new BufferedReader(f);
      int count = 0;

      String line = fr.readLine();

      while (line != null)
      {
        count++;
        line = fr.readLine();
      }
      System.out.println("Count " + count);

      if (count < 3)
      {
        return false;
      }

      fr.close();

      return true;
    }
    catch (Exception e)
    {
      e.printStackTrace();
      return false;
    }
  }

  /** *****************Setters and Getters***************** */
  protected int sleepInterval;

  public int getSleepInterval ()
  {
    return sleepInterval;
  }

  public void setSleepInterval (int sleepInterval)
  {
    this.sleepInterval = sleepInterval;
  }
}
