package app.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CsvData5 {
	//
	// This class corresponds to items, which are saved in one line of .csv file.
	// This class includes methods for saving and reading data from said .csv files.
	//
	
	Integer dt;
	Double day1;
	Double day2;
	Double day3;
	Double day4;
	Double day5;
	
	public void setDt(Integer dt) {
		this.dt = dt;
	}	
	public void setDay1(Double day1) {
		this.day1 = day1;
	}
	public void setDay2(Double day2) {
		this.day2 = day2;
	}
	public void setDay3(Double day3) {
		this.day3 = day3;
	}
	public void setDay4(Double day4) {
		this.day4 = day4;
	}
	public void setDay5(Double day5) {
		this.day5 = day5;
	}
	public Integer getDt() {
		return this.dt;
	}
	public Double getDay1() {
		return this.day1;
	}
	public Double getDay2() {
		return this.day2;
	}
	public Double getDay3() {
		return this.day3;
	}
	public Double getDay4() {
		return this.day4;
	}
	public Double getDay5() {
		return this.day5;
	}
	
	public Boolean save(String city) throws IOException {
		//
		// Saves Cn2 predictions into a .csv file.
		// If no .csv file if found, it is created.
		// File name is based on location and amount of predictions' days.
		// Returns true if data is saved.
		// Returns false if this particular data is already present in last line of .csv file.
		//
		
		if(lastDtMatch(city)) return false;
		FileWriter fw = new FileWriter(System.getProperty("user.home") + File.separator + "Cn2Prediction" + File.separator + city + "5.csv",true);
		fw.append(this.dt.toString());
		fw.append(",");
		fw.append(this.day1.toString());
		fw.append(",");
		fw.append(this.day2.toString());
		fw.append(",");
		fw.append(this.day3.toString());
		fw.append(",");
		fw.append(this.day4.toString());
		fw.append(",");
		fw.append(this.day5.toString());
		fw.append(",");
		fw.append(this.day5.toString());
		fw.append("\n");
		
		fw.flush();
		fw.close();
		
		return true;
	}
	public Boolean lastDtMatch(String city) throws IOException {
		//
		// This function exists for checking purposes.
		// Returns true, if dt in last record (line) of .csv file matches dt of the data user wants to save.
		// Prevents saving multiple identical records into .csv file.
		//
		
		File f = new File(System.getProperty("user.home") + File.separator + "Cn2Prediction" + File.separator + city +"5.csv");
		if(f.isFile()) {
			BufferedReader csvReader = new BufferedReader(new FileReader(System.getProperty("user.home") + File.separator + "Cn2Prediction" + File.separator + city + "5.csv"));
			String row;
			String[] data = null;
			
			while ((row = csvReader.readLine()) != null) {
			    data = row.split(",");
			}
			csvReader.close();
			
			if(Integer.parseInt(data[0]) == this.dt)
				return true;
			else return false;
		}
		
		else return false;
		
	}

}
