/*
 * 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 sikd.ikonsol.ctrl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import org.primefaces.PrimeFaces;
import org.primefaces.event.FileUploadEvent;
import sikd.ikonsol.ejb.session.InformasiEjbHome;
import sikd.ikonsol.model.Informasi;
import sikd.sikd5.sikd5bean.util.PropertiesLoader;

/**
 *
 * @author Imam Bhoim
 */
@ViewScoped
@Named(value = "informasiBeanCtrl")
public class InformasiBeanCtrl implements Serializable {

    Informasi informasi, overview, disclaimer, kontak;
    Informasi obj;
    private List<Informasi> listInfoApp, listDokApp, listPeraturan;

    private Date tglversi;
    private Date tgldok;
    private Date tglperaturan;

    private String pathFile;

    @EJB
    InformasiEjbHome informasiEjbHome;

    @PostConstruct
    public void init() {

        listInfoApp = informasiEjbHome.findAllInfoApp();
        listDokApp = informasiEjbHome.findAllDokApp();
        listPeraturan = informasiEjbHome.findAllPeraturanApp();

        overview = informasiEjbHome.findByIDOverview(1);

        disclaimer = informasiEjbHome.findByIDDisclaimer(1);

        kontak = informasiEjbHome.findByIDKontak(1);

        //obj = periodeEjbHome.findByKode("22");
        //periode = periodeEjbHome.createNew();
        tglversi = Calendar.getInstance().getTime();
        tgldok = Calendar.getInstance().getTime();
        tglperaturan = Calendar.getInstance().getTime();
    }

    public Informasi getInformasi() {
        return informasi;
    }

    public void setInformasi(Informasi informasi) {
        this.informasi = informasi;
    }

    public Informasi getObj() {
        return obj;
    }

    public void addVersi() {

        //periode = periodeEjbHome.createNew();
        informasi = informasiEjbHome.createNewInfoApp();
    }

    public void addDok() {

        //periode = periodeEjbHome.createNew();
        informasi = informasiEjbHome.createNewDokApp();
    }

    public void addPeraturan() {

        //periode = periodeEjbHome.createNew();
        informasi = informasiEjbHome.createNewPeraturanApp();
    }
//

    public String saveVersi() {

        informasi.setTglversi(new java.sql.Date(tglversi.getTime()));

        informasiEjbHome.saveInfoApp(informasi);

        PrimeFaces.current().executeScript("PF('wg_entryform').hide()");
        PrimeFaces.current().ajax().update(":master:dtinfo");

        listInfoApp = informasiEjbHome.findAllInfoApp();
        //this.list = service.findAll();
        return "index?faces-redirect=true";
    }

    public String saveDok() {

        informasi.setTgldok(new java.sql.Date(tgldok.getTime()));

        informasiEjbHome.saveDokApp(informasi);

        PrimeFaces.current().executeScript("PF('wg_entryform2').hide()");
        PrimeFaces.current().ajax().update(":master2:dtdok");

        listDokApp = informasiEjbHome.findAllDokApp();
        //this.list = service.findAll();
        return "index?faces-redirect=true";
    }

    public String savePeraturan() {

        informasi.setTglper(new java.sql.Date(tglperaturan.getTime()));

        informasiEjbHome.savePeraturanApp(informasi);

        PrimeFaces.current().executeScript("PF('wg_entryform').hide()");
        PrimeFaces.current().ajax().update(":master:dtper");

        listPeraturan = informasiEjbHome.findAllPeraturanApp();
        //this.list = service.findAll();
        return "index?faces-redirect=true";
    }

    public void editVersi(int id) {
        //obj = service.findByID(Integer.parseInt(id));
        obj = informasiEjbHome.findByIDInfoApp(id);

        tglversi = (Date) obj.getTglversi();

    }

    public void editDok(int id) {
        //obj = service.findByID(Integer.parseInt(id));
        obj = informasiEjbHome.findByIDDokApp(id);
        tgldok = (Date) obj.getTgldok();
    }

    public void editPer(int id) {
        //obj = service.findByID(Integer.parseInt(id));
        obj = informasiEjbHome.findByIDPeraturanApp(id);
        tglperaturan = (Date) obj.getTglper();
    }

    public void editOverview(int id) {
        //obj = service.findByID(Integer.parseInt(id));
        overview = informasiEjbHome.findByIDOverview(id);
    }

    public void editDisclaimer(int id) {
        //obj = service.findByID(Integer.parseInt(id));
        disclaimer = informasiEjbHome.findByIDDisclaimer(id);
    }

    public void editKontak(int id) {
        //obj = service.findByID(Integer.parseInt(id));
        kontak = informasiEjbHome.findByIDKontak(id);
    }

//
    public String updateVersi() {

        obj.setTglversi(new java.sql.Date(tglversi.getTime()));

        informasiEjbHome.updateInfoApp(obj);

        PrimeFaces.current().executeScript("PF('wg_entryformubah').hide()");
        PrimeFaces.current().ajax().update(":master:dtinfo");

        listInfoApp = informasiEjbHome.findAllInfoApp();
        //this.list = service.findAll();
        return "index?faces-redirect=true";
    }

    public String updateDok() {

        obj.setTgldok(new java.sql.Date(tgldok.getTime()));

        informasiEjbHome.updateDokApp(obj);

        PrimeFaces.current().executeScript("PF('wg_entryform2ubah').hide()");
        PrimeFaces.current().ajax().update(":master2:dtdok");

        listDokApp = informasiEjbHome.findAllDokApp();
        //this.list = service.findAll();
        return "index?faces-redirect=true";
    }

    public String updatePer() {

        obj.setTglper(new java.sql.Date(tglperaturan.getTime()));

        informasiEjbHome.updatePeraturanApp(obj);

        PrimeFaces.current().executeScript("PF('wg_entryformubah').hide()");
        PrimeFaces.current().ajax().update(":master:dtper");

        listPeraturan = informasiEjbHome.findAllPeraturanApp();
        //this.list = service.findAll();
        return "index?faces-redirect=true";
    }

    public void deleteVersi(int id) {
        //obj = service.findByID(Integer.parseInt(id));
        //obj = periodeEjbHome.findByKode(kode);
        informasiEjbHome.deleteInfoApp(id);
        PrimeFaces.current().ajax().update(":master:dtinfo");
        listInfoApp = informasiEjbHome.findAllInfoApp();
    }

    public void deleteDok(int id) {
        //obj = service.findByID(Integer.parseInt(id));
        //obj = periodeEjbHome.findByKode(kode);
        informasiEjbHome.deleteDokApp(id);
        PrimeFaces.current().ajax().update(":master2:dtdok");
        listDokApp = informasiEjbHome.findAllDokApp();
    }

    public void deletePer(int id) {
        //obj = service.findByID(Integer.parseInt(id));
        //obj = periodeEjbHome.findByKode(kode);
        informasiEjbHome.deletePeraturanApp(id);
        PrimeFaces.current().ajax().update(":master:dtper");
        listPeraturan = informasiEjbHome.findAllPeraturanApp();
    }

    public String updateoverview() {

        informasiEjbHome.updateOverviewApp(overview);

        PrimeFaces.current().executeScript("PF('wg_entryformoverview').hide()");
        PrimeFaces.current().ajax().update(":master2:dtdok");
        PrimeFaces.current().ajax().update(":master:dtinfo");

        overview = informasiEjbHome.findByIDOverview(1);

        listDokApp = informasiEjbHome.findAllDokApp();
        listInfoApp = informasiEjbHome.findAllInfoApp();
        //this.list = service.findAll();
        return "index?faces-redirect=true";
    }

    public String updatedisclaimer() {

        informasiEjbHome.updateDisclaimerApp(disclaimer);

        PrimeFaces.current().executeScript("PF('wg_entryformdisclaimer').hide()");

        disclaimer = informasiEjbHome.findByIDDisclaimer(1);

        //this.list = service.findAll();
        return "index?faces-redirect=true";
    }

    public String updatekontak() {

        informasiEjbHome.updateKontak(kontak);

        PrimeFaces.current().executeScript("PF('wg_entryform').hide()");

        kontak = informasiEjbHome.findByIDKontak(1);

        //this.list = service.findAll();
        return "index?faces-redirect=true";
    }

    public String alamatPath() {
        String uploadPath = "";
        Properties pr;
        try {
            pr = PropertiesLoader.loadProperties("sikd.properties");
            uploadPath = pr.getProperty("uploadPath");

        } catch (Exception ex) {
            Logger.getLogger(InformasiBeanCtrl.class.getName()).log(Level.SEVERE, null, ex);
        }

        return uploadPath;

    }

    public void download(String fileName) throws Exception {
        Properties pr = PropertiesLoader.loadProperties("sikd.properties");
        String foldernya = pr.getProperty("uploadPath") + File.separator;
        File file = new File(foldernya + File.separator + fileName);
        BufferedInputStream inp = null;
        BufferedOutputStream out = null;
        FacesContext fcontext = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) fcontext.getExternalContext().getResponse();
        try {
            inp = new BufferedInputStream(new FileInputStream(file), 10240);

            response.reset();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Length", String.valueOf(file.length()));
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            out = new BufferedOutputStream(response.getOutputStream(), 10240);
            byte[] buffer = new byte[10240];
            int length;
            while ((length = inp.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            out.flush();
        } finally {
            if (inp != null) {
                inp.close();
            }
            if (out != null) {
                out.close();
            }
        }
        fcontext.responseComplete();
    }

    public String saveUploadDok(FileUploadEvent event) throws Exception {
        System.out.println(event.getFile().getFileName() + " is uploaded.");
        // TODO Auto-generated method stub
        Properties pr = PropertiesLoader.loadProperties("sikd.properties");
        String uploadPath = pr.getProperty("uploadPath");

        //ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
        //String resHomeImgPath = servletContext.getRealPath("G:\\E_KONSOLIDASI\\Dokumen");
        //pathFile = uploadPath;
        try (InputStream input = event.getFile().getInputstream()) {
            String fileName = event.getFile().getFileName();

            String names = obj.getIddokapp() + "_" + obj.getNamadok() + ".pdf";
            String name = names.replaceAll(" ", "_").trim();

            // String ext = fileName.substring(fileName.lastIndexOf('.'),fileName.length());
//            File a = new File(resHomeImgPath, name);
//            if (a.exists() && a.isFile()) {
//                a.delete();
//                Files.copy(input, new File(resHomeImgPath, name).toPath());
//
//            } else {
//                Files.copy(input, new File(resHomeImgPath, name).toPath());
//
//            }
            File a = new File(uploadPath, name);
            if (a.exists() && a.isFile()) {
                a.delete();
                Files.copy(input, new File(uploadPath, name).toPath());

            } else {
                Files.copy(input, new File(uploadPath, name).toPath());

            }

            FacesMessage msg = new FacesMessage("Success", event.getFile().getFileName() + "Is Upload.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            obj.setFileuploaddok(name);
            informasiEjbHome.uploadFileDok(obj);
            //   this.listpengajuan = service.findByHistoryAllKepangkatanIdPengajuan();
            //   listpengajuan = service.findByHistoryKepangkatanIdPengajuan(obj.getEmpid());

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "index?faces-redirect=true";

    }

    public String saveUploadPer(FileUploadEvent event) throws Exception {
        System.out.println(event.getFile().getFileName() + " is uploaded.");
        // TODO Auto-generated method stub
        Properties pr = PropertiesLoader.loadProperties("sikd.properties");
        String uploadPath = pr.getProperty("uploadPath");

        //ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
        //String resHomeImgPath = servletContext.getRealPath("/resources/upload/pdfper");
        //pathFile = uploadPath;
        try (InputStream input = event.getFile().getInputstream()) {
            String fileName = event.getFile().getFileName();

            String names = obj.getIdper() + "_" + obj.getNamaper() + ".pdf";
            String name = names.replaceAll(" ", "_").trim();

            // String ext = fileName.substring(fileName.lastIndexOf('.'),fileName.length());
//            File a = new File(resHomeImgPath, name);
//            if (a.exists() && a.isFile()) {
//                a.delete();
//                Files.copy(input, new File(resHomeImgPath, name).toPath());
//
//            } else {
//                Files.copy(input, new File(resHomeImgPath, name).toPath());
//
//            }
            File a = new File(uploadPath, name);
            if (a.exists() && a.isFile()) {
                a.delete();
                Files.copy(input, new File(uploadPath, name).toPath());

            } else {
                Files.copy(input, new File(uploadPath, name).toPath());

            }

            FacesMessage msg = new FacesMessage("Success", event.getFile().getFileName() + "Is Upload.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            obj.setFileuploadper(name);
            informasiEjbHome.uploadFilePer(obj);
            //   this.listpengajuan = service.findByHistoryAllKepangkatanIdPengajuan();
            //   listpengajuan = service.findByHistoryKepangkatanIdPengajuan(obj.getEmpid());

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "index?faces-redirect=true";

    }

    public void reloaddok() {
        listDokApp = informasiEjbHome.findAllDokApp();
        listInfoApp = informasiEjbHome.findAllInfoApp();

    }

    public void reloadper() {
        listPeraturan = informasiEjbHome.findAllPeraturanApp();

    }
//
//    public void edit(String kode) {
//        //obj = service.findByID(Integer.parseInt(id));
//        obj = periodeEjbHome.findByKode(kode);
//
//    }
//
//    public void delete(String kode) {
//        //obj = service.findByID(Integer.parseInt(id));
//        //obj = periodeEjbHome.findByKode(kode);
//        periodeEjbHome.delete(kode);
//        PrimeFaces.current().ajax().update(":master:dtperiod");
//        list = periodeEjbHome.findAll();
//        // this.list = service.findAll();
//
//    }

    public void setObj(Informasi obj) {
        this.obj = obj;
    }

    public List<Informasi> getListInfoApp() {
        return listInfoApp;
    }

    public void setListInfoApp(List<Informasi> listInfoApp) {
        this.listInfoApp = listInfoApp;
    }

    public List<Informasi> getListDokApp() {
        return listDokApp;
    }

    public void setListDokApp(List<Informasi> listDokApp) {
        this.listDokApp = listDokApp;
    }

    public List<Informasi> getListPeraturan() {
        return listPeraturan;
    }

    public void setListPeraturan(List<Informasi> listPeraturan) {
        this.listPeraturan = listPeraturan;
    }

    public Date getTglversi() {
        return tglversi;
    }

    public void setTglversi(Date tglversi) {
        this.tglversi = tglversi;
    }

    public Date getTgldok() {
        return tgldok;
    }

    public void setTgldok(Date tgldok) {
        this.tgldok = tgldok;
    }

    public Date getTglperaturan() {
        return tglperaturan;
    }

    public void setTglperaturan(Date tglperaturan) {
        this.tglperaturan = tglperaturan;
    }

    public Informasi getOverview() {
        return overview;
    }

    public void setOverview(Informasi overview) {
        this.overview = overview;
    }

    public Informasi getDisclaimer() {
        return disclaimer;
    }

    public void setDisclaimer(Informasi disclaimer) {
        this.disclaimer = disclaimer;
    }

    public String getPathFile() {
        return pathFile;
    }

    public void setPathFile(String pathFile) {
        this.pathFile = pathFile;
    }

    public Informasi getKontak() {
        return kontak;
    }

    public void setKontak(Informasi kontak) {
        this.kontak = kontak;
    }

}
