package com.example.upload01;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;



//https://examples.javacodegeeks.com/core-java/writeread-csv-files-in-java-example/

public class CSV_write 
{
			//Delimiter used in CSV file
		    private static final String COMMA_DELIMITER = ",";
		    private static final String NEW_LINE_SEPARATOR = "\n";
		    //CSV file header
		    private static final String FILE_HEADER = "id,firstName,lastName,gender,age";
		    
		    public static void writeCsvFile(String fileName)
		    {
		    	CSV student1 = new CSV(1, "Ahmed", "Mohamed", "M", "25" , "", "");
		    	CSV student2 = new CSV(2, "Pauld", "un", "M", "25" , "", "");
		    	CSV student3 = new CSV(3, "Jacques", "deux", "M", "25" , "", "");
		    	CSV student4 = new CSV(4, "Remy", "trois", "M", "25" , "", "");
		    		         
		    	ArrayList<CSV> lignes =new ArrayList<CSV>();
		    	
		    	lignes.add(student1);
		    	lignes.add(student2);
		    	lignes.add(student3);
		    	lignes.add(student4);
		    	
		    	FileWriter fileWriter = null;
		    	
		    	try 
		    	{
						fileWriter = new FileWriter(fileName);
						fileWriter.append(FILE_HEADER.toString());
						fileWriter.append(NEW_LINE_SEPARATOR);
						
		    		 	Iterator itr=lignes.iterator();	
		    		 	while(itr.hasNext())
		    		 	{  
		    			    CSV st=(CSV)itr.next();  
		    			    st.getfixe();
		    			}   
		    		 
						
						for(int i = 0; i < lignes.size(); i++)
						{
							fileWriter.append(String.valueOf(lignes.get(i).getId()));
							fileWriter.append(COMMA_DELIMITER);
							fileWriter.append(lignes.get(i).getnom());
							fileWriter.append(COMMA_DELIMITER);
							fileWriter.append(lignes.get(i).getprenom());
							fileWriter.append(COMMA_DELIMITER);
							fileWriter.append(lignes.get(i).getadresse());
							fileWriter.append(COMMA_DELIMITER);
							fileWriter.append(String.valueOf(lignes.get(i).getemail()));
							fileWriter.append(NEW_LINE_SEPARATOR);
						
							
						}
					
				} 
		    	
		    	catch (Exception e)
		    	{
					System.out.println("Error in CsvFileWriter !!!");
					e.printStackTrace();
				} 
		    	
		    	finally
		    	{
					
					try
					{
						fileWriter.flush();
						fileWriter.close();
					} catch (IOException e)
					
					{
						System.out.println("Error while flushing/closing fileWriter !!!");
		                e.printStackTrace();
					}
					
				}
		    		       
		    	
		 } //
	
	
}
