/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package testmeetup;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;

/**
 * Class that holds all the operations to operate with files: open, close, append, search...
 * @author Oriol
 */
public class FileUtils {

    /**
     * Saves data given a text and a correct fileName path. This operation will replace an exisiting file.
     * It also replaces a specific String that sometimes occurs when saving files with JSONObjects that makes the open operation on those files give an error.
     * @param text Data in Text Format to be saved in the file.
     * @param fileName Name of the file to save data, existent or not.
     */
    public static void saveData(String text, String fileName){
        //Having multiple querys results in a ...}][{... where the parser doesn't know what to do. Replace that with },{
        text = text.replaceAll("\\}\\]\\[\\{", "},{");
        try{
            //If the function is called with null parameter fileName, save as generic File + Timestamp. The folder DataFiles has to exist.
            if(fileName == null){ 
                SimpleDateFormat ft = new SimpleDateFormat ("yyyyMMddhhmmss");
                Date now = new Date();
                fileName = ".\\DataFiles\\File " + ft.format(now) + ".txt";
                System.out.println("FILE SAVED WITHOUT NAME: "  + fileName);
            }
            PrintWriter out = new PrintWriter(fileName);
            
            out.println(text);
            out.close();        
        } catch (Exception ex) {
            Logger.getLogger(MeetupDataManager.class.getName()).log(Level.SEVERE, null, ex);
        }   
        System.out.println("FILE SAVED AS: "  + fileName);
    }
    
    
    /**
     * Loads data from fileName in JSONArray format.
     * @param fileName Name of the file we want to read the data.
     * @return Data in JSONArray format.
     */
    public static JSONArray loadData(String fileName){
        JSONParser parser = new JSONParser();
        JSONArray jsonData = null;
        try{
            if(fileName == null){
                System.out.println("ERROR! A FILE WAS LOADED WITHOUT NAME!");
            }
            Object in = parser.parse(new FileReader(fileName));
            
            jsonData = (JSONArray) in;
        } catch (Exception ex) {
            Logger.getLogger(MeetupDataManager.class.getName()).log(Level.SEVERE, null, ex);
        }   
        System.out.println("FILE LOADED AS: "  + fileName);
        return jsonData;
    }
    
    /**
     * Loads data from fileName in TXT format.
     * @param fileName Name of the file we want to read the data.
     * @return Data in TXT format.
     */
    public static List<String> loadDataTxt(String fileName){
        BufferedReader br;
        List<String> lines = null;
        try{
            if(fileName == null){
                fileName = ".\\DataFiles\\Los Angeles\\Events4.txt";
                System.out.println("FILE LOADED WITHOUT NAME!");
            }
            br = new BufferedReader(new FileReader(fileName));
            lines = br.lines().collect(Collectors.toList());
            br.close();
        } catch (Exception ex) {
            Logger.getLogger(MeetupDataManager.class.getName()).log(Level.SEVERE, null, ex);
        }   
        System.out.println("FILE LOADED AS: "  + fileName);
        return lines;
    }
    
    /**
     * Gets all files in folder that follows a special pattern of FileName. The pattern is: pattern + i + ".txt", where "i" is int autoincremental.
     * The function searches until it cant find a file with some i, then stops. So it wont find "test4.txt" if "test3.txt" doesnt exist.
     * @param folder Name of the forder to search on.
     * @param pattern Pattern of the files to search on.
     * @return Array of FileNames that fit the pattern.
     */
    public static ArrayList<String> getFilesByPattern(String folder, String pattern){
        ArrayList<String> files = new ArrayList<>();
        boolean exists = true;
        String file;
        int i = 1;
        while(exists){
            file = folder.concat("\\").concat(pattern).concat(Integer.toString(i)).concat(".txt");
            File f = new File(file);
            if(f.exists() && !f.isDirectory()) { 
               files.add(file);
               i++;
            }else{
                exists = false;
            }
        }
        System.out.println("ALL FILES FOUND:" + files.toString());
        return files;
    }
    
    /**
     * Uses getFilesByPattern to search all files named "RSVPx.txt", with x being any number.
     * @param folder Folder to search on.
     * @return FileNames that fit the pattern.
     */
    public static ArrayList<String> getAllRSVPS(String folder){
        return getFilesByPattern(folder,"RSVP");
    }

    /**
     * Uses getFilesByPattern to search all files named "Eventsx.txt", with x being any number.
     * @param folder Folder to search on.
     * @return FileNames that fit the pattern.
     */    
    public static ArrayList<String> getAllEvents(String folder){
        return getFilesByPattern(folder,"Events");
    }
    
    /**
     * Uses getFilesByPattern to search all files named "FilteredRSVPx.txt", with x being any number.
     * @param folder Folder to search on.
     * @return FileNames that fit the pattern.
     */ 
    public static ArrayList<String> getAllFilteredRSVP(String folder){
        return getFilesByPattern(folder,"FilteredRSVP");
    }
    
    /**
     * Uses getFilesByPattern to search all files named "Membersx.txt", with x being any number.
     * @param folder Folder to search on.
     * @return FileNames that fit the pattern.
     */
    public static ArrayList<String> getAllMembers(String folder){
        return getFilesByPattern(folder,"Members");
    }
    
    /**
     * Given a path of a file, gets the inmediate parent folder.
     * @param file
     * @return 
     */
    public static String getFolder(String file){
        return file.substring(0,file.lastIndexOf("\\")+1);
    }
    
}
