package utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;

/**
 * Classe encarregada de guardar fitxers de les tasques i entregues a disc
 */
public class FileManager {
    private String path;
    private String subjectName, taskName, userName;
    private boolean submission;
    private String[] lastFilemime;
    
    private String tempPath, savedPath;
    
    public FileManager(String dir, String subjName, String taskName, String userName, boolean sub){
        this.path = dir;
        this.subjectName = subjName;
        this.taskName = taskName;
        this.userName = userName;
        this.submission = sub;
        
        setTempPath();
        setSavedPath();
        
        System.out.println("SavedPath set to: ");
        System.out.println(savedPath);
        System.out.println("TempPath set to: ");
        System.out.println(tempPath);
    }
    
    public boolean cleanTempPath(){
        return cleanPath(tempPath);
    }
    
    public boolean cleanSavedPath(){
        return cleanPath(savedPath);
    }
    
    private boolean cleanPath(String path){
        File dirFile = new File(path);
        if (dirFile.exists()) {
            try {
                FileUtils.cleanDirectory(dirFile);
            } catch (IOException ex) {
                return false;
            }
        } else {
            dirFile.mkdirs();
        }
        return true;
    }
    
    public boolean createTempFile(File f) throws IOException{
        return createTempFile(f.getName(), file2ByteArray(f));
    }
    public boolean createTempFile(String filename, String content) throws IOException{
        return createTempFile(filename, string2ByteArray(content));
    }
    public boolean createTempFile(String filename, byte[] content) throws IOException{
        File f;
        try {
            f = byteArray2File(content, tempPath + filename);
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
            return false;
        }
        lastFilemime = readFileMime(f).split("/");

        return true;
    }
    
    public boolean moveAllTempToSaved(){
        cleanSavedPath();

        try {
            Files.move(new File(tempPath).toPath(),
                    new File(savedPath).toPath(),
                    java.nio.file.StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception ex) {
            System.out.println("ERROR MOVING FROM\n"+tempPath+"\nTO\n"+savedPath);

            return false;
        }
        return true;
    }
    
    
    public String setTempPath(){
        tempPath = path+"/WEB-INF/tasks/temp/";
        tempPath += subjectName +"/";
        tempPath += taskName +"/";
        if (submission)
            tempPath += "submissions/";
        tempPath += userName +"/";
        return tempPath;
    }
    
    public String setSavedPath(){
        savedPath = path+"/WEB-INF/tasks/";
        savedPath += subjectName +"/";
        savedPath += taskName +"/";
        if (submission)
            savedPath += "submissions/";
        savedPath += userName +"/";
        return savedPath;
    }
    
    private byte[] file2ByteArray(File f) throws IOException{
        return Files.readAllBytes(f.toPath());
    }
    
    private byte[] string2ByteArray(String s) throws IOException{
        return s.getBytes();
    }
    
    private File byteArray2File(byte[] data, String path) throws IOException{
        File f = new File(path);
        
        FileOutputStream fos = new FileOutputStream(f.getAbsolutePath());
        fos.write(data);
        fos.close();
        return f;
    }
    
    private String readFileMime(File file) throws IOException{
        ProcessBuilder builder = new ProcessBuilder("file","-b","--mime-type",file.getAbsolutePath());

        final Process process = builder.start();
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line = br.readLine();

        return line;
    }
    
    public String[] getFileMime(){
        return lastFilemime;
    }
}
