import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TimerTask;
import java.io.File;
import java.lang.String;
/*
 * Determines when to take readings, store readings and upload files to the server
 */
public class ClientTimerTask extends TimerTask{

	File dir = new File(PropertyFileValues.destination_dir);
	private SystemParameters sysparams;
	FileHandler filehandler = new FileHandler();
	ClientServerSync csync = new ClientServerSync();
	List list = new ArrayList(); 
	public static String old_date="null";
	public static String new_date="null";
	public static int file_count=0;
	public int connect_count=30;

	public ClientTimerTask(SystemParameters sysparams){
		this.sysparams=sysparams;
	}


	public void run() {

		// TODO Auto-generated method stub
		list=sysparams.Scheduler();

		filehandler.storetempFiles(list,String.valueOf(list.get(0)).substring(0,10));

		new_date = String.valueOf(list.get(0)).substring(0,10);

		Arrays.sort(PropertyFileValues.file_list);
		System.out.println("Array search result"+Arrays.binarySearch(PropertyFileValues.file_list,new_date ));


		file_count=0;
		for (int i=0; i<(PropertyFileValues.file_list).length; i++) {
			// Get filename of file or directory
			System.out.println(PropertyFileValues.file_list[i]);
			if ((PropertyFileValues.file_list[i]).contains(".txt")){
				file_count++;
			}
		}

		//if it is a new day...read the data directory again to check for new files
		if(!old_date.equals(new_date)){
			PropertyFileValues.file_list=dir.list();
		}

		if (file_count>1){
			if (connect_count>0){
				connect_count=connect_count-1;
				for (int i=0; i<(PropertyFileValues.file_list).length; i++) {
					// Get filename of file or directory
					if ((PropertyFileValues.file_list[i]).contains(".txt")&&!(PropertyFileValues.file_list[i]).contains(new_date)){
						if ((csync.connect(String.valueOf(list.get(8)),PropertyFileValues.file_list[i])).equals("success")){
							//move the file
							System.out.println("File Transfer Success");
							connect_count=20;
							filehandler.moveFileToArchive(PropertyFileValues.file_list[i]);
							try
							{
								Thread.sleep(1000); // do nothing for 1000 miliseconds (1 second)
							}
							catch(InterruptedException e)
							{
								e.printStackTrace();
							}
						}
					}
				}
			}
			PropertyFileValues.file_list=dir.list();
			old_date=new_date;

		}
	}

}

