/*
 * 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 br.com.elotech.websaude.integracao.cnes.ui;

import com.vaadin.ui.Notification;
import com.vaadin.ui.Upload.Receiver;
import com.vaadin.ui.Upload.SucceededEvent;
import com.vaadin.ui.Upload.SucceededListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.output.NullOutputStream;

/**
 *
 * @author elotech
 */
public class CnesUploader implements Receiver, SucceededListener {

    private static final long serialVersionUID = 1L;

    String filename = "temporario", tempFilePath = "/tmp/";
    public static File file;

    @Override
    public OutputStream receiveUpload(String filename, String mimeType) {
        this.filename = filename;
        FileOutputStream fos;
        System.out.println(System.getProperty("user.dir"));
        file = new File(System.getProperty("user.dir")+"/"+filename);

        try {
            fos = new FileOutputStream(file);
        } catch (java.io.FileNotFoundException e) {
            Notification.show("Ocorreu um erro!", "Por favor, contacte o suporte para reportar.\n" + e.getMessage(), Notification.Type.ERROR_MESSAGE);
            Logger.getLogger(CnesUploader.class.getName()).log(Level.SEVERE, null, e);
            e.printStackTrace();
            return new NullOutputStream();
        }

        return fos;
    }

    @Override
    public void uploadSucceeded(SucceededEvent event) {
        Notification.show("Upload realizado com sucesso: " + file.getPath(), Notification.Type.TRAY_NOTIFICATION);
    }

    private String ParseFileName(String filename) {
        String MyFileName = "";
//searching the last position of path delimiter
        int lastPathDivider = filename.lastIndexOf("\\");

//get the last substring of filename string
        MyFileName = filename.substring(lastPathDivider + 1);

        return MyFileName;
    }

}
