import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

public class ImportExport {
	public static void exportWithDialog(ActionList list) {
		JFileChooser chooser = new JFileChooser();
		FileNameExtensionFilter filter = new FileNameExtensionFilter("Array data", "adata");
		chooser.setFileFilter(filter);
		chooser.setApproveButtonText("Exporter");
		int returnVal = chooser.showOpenDialog(null);
		if(returnVal == JFileChooser.APPROVE_OPTION)
			export(list, chooser.getSelectedFile().getPath());
	}
	private static void export(ActionList list, String path) {
		String str = list.getLeftDeltaArray() + "\n" + list.getRightDeltaArray() + "\n" + list.getLeftDelaiArray() + "\n" + list.getRightDelaiArray();
		
		if(!path.endsWith(".adata"))
			path += ".adata";
		BufferedWriter bufferedWriter = null;
		try {
			File file = new File(path);
			if (!file.exists())
				file.createNewFile();
			bufferedWriter = new BufferedWriter(new FileWriter(file));
			bufferedWriter.write(str);
			bufferedWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static ActionList importsWithDialog() {
		JFileChooser chooser = new JFileChooser();
		FileNameExtensionFilter filter = new FileNameExtensionFilter("Array data", "adata");
		chooser.setFileFilter(filter);
		chooser.setMultiSelectionEnabled(false);
		chooser.setApproveButtonText("Importer");
		int returnVal = chooser.showOpenDialog(null);
		if(returnVal == JFileChooser.APPROVE_OPTION && chooser.getSelectedFile().exists() && chooser.getSelectedFile().isFile())
			return imports(chooser.getSelectedFile().getPath());
		if(returnVal == JFileChooser.APPROVE_OPTION)
			JOptionPane.showMessageDialog(null, "You have to choose an exisiting file", "Import error", JOptionPane.ERROR_MESSAGE);
		return null;
	}
	private static ActionList imports(String path) {
		try {
			byte[] encoded = Files.readAllBytes(Paths.get(path));
			String str = new String(encoded, Charset.defaultCharset());
			
			long[][] longList = Util.getArraysFromImport(str);
			if(longList == null) {
				JOptionPane.showMessageDialog(null, "The choosen file is invalid or currupted", "Import error", JOptionPane.ERROR_MESSAGE);
				return null;
			}
			int[][] intList = new int[2][longList[0].length];
			for(int i=0; i<2; i++)
				for(int j=0; j<longList[0].length; j++)
					intList[i][j] = (int) longList[i][j];
			
			return new ActionList(intList[0], intList[1], longList[2], longList[3]);
		} catch (IOException ignored) {}
		return null;
	}
}
