package sikd.sikd5.ctrl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.naming.Context;
import javax.servlet.http.HttpServletResponse;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

import sikd.sikd5.model.UploadFileObj;
import sikd.sikd5.security.LoginMB;
import sikd.sikd5.sikd5bean.tabel.Pemda;
import sikd.sikd5.sikd5bean.tabel.TahunAnggaran;
import sikd.sikd5.sikd5bean.tabel.UploadFile;
import sikd.sikd5.sikd5bean.util.PropertiesLoader;
import sikd.sikd5.sikd5bean.util.SIKDUtil;
import sikd.sikd5.sikd5bean.util.ServerUtil;
import sikd.sikd5.sikd5bean.util.SikdSessionUtil;
import sikd.sikd5.sikd5ejb.session.SettingsSessionBeanRemote;
import sikd.sikd5.sikd5ejb.session.UploadFileSessionBeanRemote;
import sikd.sikd5.sikd5ejb.session.login.LoginSessionBeanRemote;

import static com.google.common.io.ByteStreams.copy;

/**
 * @author : agus
 * @tanggal : Dec 13, 2018
 */
@Named
@SessionScoped
public class UploadHcCtrl implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	String idComboYear = "cbYear";
	TahunAnggaran selectedYear = new TahunAnggaran();
	TahunAnggaran yearNull = new TahunAnggaran();
	boolean editMode = false;
	List<TahunAnggaran> tahuns;
	String updateYear = "cbPemda";
	String idPanelYear = "pnTahun";
	boolean viewYear = true ;

	String idComboPemda = "cbPemda";
	Pemda selectedPemda = new Pemda();
	Pemda pemdaNull = new Pemda();
	List<Pemda> pemdas = new ArrayList<Pemda>();
	String updatePemda = "panelrinci";
	String idPanelPemda = "pnPemda";
	boolean viewPemda = true;

	List<UploadFileObj> uploadFiles= new ArrayList<UploadFileObj>();

	String selectedIKD = "";
	String selectedIkdNickname = "";
	@Inject
//	@ManagedProperty(value = "#{loginMB}")
	LoginMB loginMB;
	SettingsSessionBeanRemote settingsSes;
	UploadFileSessionBeanRemote uploadFileSes;
	LoginSessionBeanRemote sessionLogin;
	String blueSubTitle = "";

	@PostConstruct
	public void init() throws Exception {
		Context ctxOffice = ServerUtil.getOfficeContextV3();
		SettingsSessionBeanRemote settingsSes = (SettingsSessionBeanRemote) ctxOffice
				.lookup(SikdSessionUtil.SETTINGS_SESSION);
		uploadFileSes = (UploadFileSessionBeanRemote) ctxOffice.lookup(SikdSessionUtil.UPLOAD_FILE_SESSION);
		sessionLogin = (LoginSessionBeanRemote) ctxOffice
				.lookup(SikdSessionUtil.LOGIN_SESSION);
		tahuns = settingsSes.getTahuns();

	}

	private void setFile(UploadFile ff) {
		int ii = 0;
		boolean find = false;

		if (ff != null) {
			if (ff.getKodeikd() == null) {
				ff.setKodeikd("");
			}
			while (ii < uploadFiles.size() && find == false) {
				if ((uploadFiles.get(ii).getIkd() == null ? "" : uploadFiles.get(ii).getIkd().trim())
						.equals(ff.getIkd() == null ? "" : ff.getIkd().trim()) ||
						(uploadFiles.get(ii).getIkdNickname() == null ? ""
								: uploadFiles.get(ii).getIkdNickname().trim())
										.equals(ff.getKodeikd() == null ? "" : ff.getKodeikd().trim())) {
					File f = new File(ff.getFilename() == null ? "" : ff.getFilename().trim());
					if (f.isFile()) {
						uploadFiles.get(ii).setId(ff.getId());
						uploadFiles.get(ii).setFilename(ff.getFilename().trim());
						uploadFiles.get(ii).setKdsatker(ff.getKdsatker().trim());
						uploadFiles.get(ii).setTahun(ff.getTahun());
						uploadFiles.get(ii).setTglupload(ff.getTglupload());
					}
					find = true;
				}
				ii++;
				// }
			}
		}
	}

	public void initUploadFiles() {
		uploadFiles.clear();
		uploadFiles.add(new UploadFileObj("Rekening Sub Registri", "SUB01"));
		uploadFiles.add(new UploadFileObj("Posisi Kas Bulan 1", "PKB01"));
		uploadFiles.add(new UploadFileObj("Posisi Kas Bulan 2", "PKB02"));
		uploadFiles.add(new UploadFileObj("Posisi Kas Bulan 3", "PKB03"));
		uploadFiles.add(new UploadFileObj("Posisi Kas Bulan 4", "PKB04"));
		uploadFiles.add(new UploadFileObj("Posisi Kas Bulan 5", "PKB05"));
		uploadFiles.add(new UploadFileObj("Posisi Kas Bulan 6", "PKB06"));
		uploadFiles.add(new UploadFileObj("Posisi Kas Bulan 7", "PKB07"));
		uploadFiles.add(new UploadFileObj("Posisi Kas Bulan 8", "PKB08"));
		uploadFiles.add(new UploadFileObj("Posisi Kas Bulan 9", "PKB09"));
		uploadFiles.add(new UploadFileObj("Posisi Kas Bulan 10", "PKB10"));
		uploadFiles.add(new UploadFileObj("Posisi Kas Bulan 11", "PKB11"));
		uploadFiles.add(new UploadFileObj("Posisi Kas Bulan 12", "PKB12"));

		uploadFiles.add(new UploadFileObj("Perkiraan Belanja Bulan 1", "PBB01"));
		uploadFiles.add(new UploadFileObj("Perkiraan Belanja Bulan 2", "PBB02"));
		uploadFiles.add(new UploadFileObj("Perkiraan Belanja Bulan 3", "PBB03"));
		uploadFiles.add(new UploadFileObj("Perkiraan Belanja Bulan 4", "PBB04"));
		uploadFiles.add(new UploadFileObj("Perkiraan Belanja Bulan 5", "PBB05"));
		uploadFiles.add(new UploadFileObj("Perkiraan Belanja Bulan 6", "PBB06"));
		uploadFiles.add(new UploadFileObj("Perkiraan Belanja Bulan 7", "PBB07"));
		uploadFiles.add(new UploadFileObj("Perkiraan Belanja Bulan 8", "PBB08"));
		uploadFiles.add(new UploadFileObj("Perkiraan Belanja Bulan 9", "PBB09"));
		uploadFiles.add(new UploadFileObj("Perkiraan Belanja Bulan 10", "PBB10"));
		uploadFiles.add(new UploadFileObj("Perkiraan Belanja Bulan 11", "PBB11"));
		uploadFiles.add(new UploadFileObj("Perkiraan Belanja Bulan 12", "PBB12"));

	}

	public void download(String fileName) throws IOException {
		File file = new File(fileName);
		if (file.isFile()) {
			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.setHeader("Content-Length", String.valueOf(file.length()));
				String realFileName = fileName.substring(fileName.lastIndexOf("/") + 1);
				response.setHeader("Content-Disposition", "inline;filename=\"" + realFileName + "\"");

				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 void onYearChange() {
		try {
			pemdas.clear();
//			System.out.println("loginmb");
//			System.out.println(loginMB);
//			System.out.println("selectedYear");
//			System.out.println(selectedYear);
			List<Pemda> pemdaTh = loginMB.getPemdaByTahuns(selectedYear.getTahun());
			List<Pemda> pemdaWil = new ArrayList<Pemda>();
			if (loginMB.getTuserAccount().getWilayah() != null) {
				if (loginMB.getTuserAccount().getWilayah().getPemdas() != null) {
					pemdaWil = loginMB.getTuserAccount().getWilayah().getPemdas();
				}
			}
			if (loginMB.getTuserAccount().getPemda() != null) {
				boolean ketemu = false;
				for (Pemda pemda : pemdaWil) {
					if (pemda.getKodeSatker().equals(loginMB.getTuserAccount().getPemda().getKodeSatker())) {
						ketemu = true;
						break;
					}
				}
				if (!ketemu) {
					pemdaWil.add(loginMB.getTuserAccount().getPemda());
				}
			}
			for (Pemda pemdaW : pemdaWil) {
				for (Pemda pemdaT : pemdaTh) {
					if (pemdaW.getKodeSatker().equals(pemdaT.getKodeSatker())) {
						pemdas.add(pemdaW);
						break;
					}
				}
			}
		} catch (

		Exception e) {
			e.printStackTrace();
		}
	}

	public void onPemdaChange() {
		initUploadFiles();
//		System.out.println("uploadFiles.size()");
//		uploadFiles.size();
		if (selectedYear != null && selectedYear.getTahun() > 0) {
			blueSubTitle = "TAHUN ANGGARAN " + selectedYear.getTahun();
		}
		if (selectedYear != null && selectedYear.getTahun() > 0
				&& selectedPemda != null && selectedPemda.getId() > 0) {
			blueSubTitle = "TAHUN ANGGARAN " + selectedYear.getTahun() + " "
					+ selectedPemda.getNamaPemda().toUpperCase();
			try {
				List<UploadFile> files = uploadFileSes.getAllUploadFiles(selectedPemda.getKodeSatker(),	selectedYear.getTahun());
				for (UploadFile ff : files) {
					setFile(ff);
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	}

	@SuppressWarnings("ConvertToTryWithResources")
	public void handleFileUpload(FileUploadEvent e) {
		try {
//            short yy = 0;
			if (selectedYear != null && selectedYear.getTahun() > 0
					&& selectedPemda != null && selectedPemda.getId() > 0 && selectedIKD != null
					&& selectedIkdNickname != null) {
//                yy = Short.parseShort(getSelectedYear());
//            }

//				OutputStream outputStream;
				UploadedFile f = e.getFile();
//                String fileName = uploadPath  + selectedPemda.getKodeProvinsi() + "." + selectedPemda.getKodePemda() + "_" +selectedIKD + "_" + selectedYear.getTahun()+".pdf";
//                String fileName = SIKDUtil.uploadPathHcnya(uploadPath, selectedYear.getTahun()) + selectedYear.getTahunAsString()
//                        + selectedPemda.getKodeSatker() + selectedIkdNickname + ".pdf";
				Date tgl = new Date();
				String tgls = SIKDUtil.dateToString1(tgl);
				String uploadPath = ((Properties) PropertiesLoader.loadProperties("sikd.properties"))
						.getProperty("uploadPath");
				SIKDUtil.cekFolder(SIKDUtil.uploadPathHcnya(uploadPath, selectedYear.getTahun(), selectedIkdNickname.substring(0, 3)));
				String fileName = SIKDUtil.uploadPathHcnya(uploadPath, selectedYear.getTahun(),
						selectedIkdNickname.substring(0, 3)) +
						selectedYear.getTahunAsString() + selectedPemda.getKodeSatker() + selectedIkdNickname
						+ "_" + tgls
						+ ".pdf";

//    			File ff = new File(fileName);

				fileName = fileName.replace("//", "/");
				fileName = fileName.replace("\\\\", "\\");
//                String fileName = uploadPath + selectedYear.getTahun()+selectedPemda.getKodeSatker() + selectedIkdNickname +".pdf";
				InputStream inps = f.getInputstream();
				OutputStream outs = new FileOutputStream(fileName);
//                System.out.println(fileName);

//                SIKDUtil.cekFolder(SIKDUtil.uploadPathHcnya(uploadPath, selectedYear.getTahun()));
                copy(inps, outs);
				inps.close();
				outs.close();
//                UploadFile uf = new UploadFile(selectedYear.getTahun(), selectedIKD, selectedPemda.getKodeSatker(), fileName, new Date(), selectedIkdNickname);

//                uploadSession.addUploadFile(uf);
//                selectedIKD = null;
				SIKDUtil.cekFolder(SIKDUtil.uploadPathHcnya(uploadPath, selectedYear.getTahun(),
						selectedIkdNickname.substring(0, 3)));
//    			FileOutputStream fos = new FileOutputStream(ff);
//				outs.write(inps.read());
//				outs.flush();
//				outs.close();
//				inps.close();
				Context ctxOffice = ServerUtil.getOfficeContextV3();
				UploadFileSessionBeanRemote session = (UploadFileSessionBeanRemote) ctxOffice
						.lookup(SikdSessionUtil.UPLOAD_FILE_SESSION);
				UploadFile uf = new UploadFile(selectedYear.getTahun(), "pdf", selectedPemda.getKodeSatker(), fileName,
						tgl, selectedIkdNickname);
				session.insert(uf);
				onPemdaChange();
//                initData();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	public TahunAnggaran getSelectedYear() {
		return selectedYear;
	}

	public void setSelectedYear(TahunAnggaran selectedYear) {
		this.selectedYear = selectedYear;
	}

	public TahunAnggaran getYearNull() {
		return yearNull;
	}

	public void setYearNull(TahunAnggaran yearNull) {
		this.yearNull = yearNull;
	}

	public List<TahunAnggaran> getTahuns() {
		return tahuns;
	}

	public void setTahuns(List<TahunAnggaran> tahuns) {
		this.tahuns = tahuns;
	}

	public Pemda getSelectedPemda() {
		return selectedPemda;
	}

	public void setSelectedPemda(Pemda selectedPemda) {
		this.selectedPemda = selectedPemda;
	}

	public Pemda getPemdaNull() {
		return pemdaNull;
	}

	public void setPemdaNull(Pemda pemdaNull) {
		this.pemdaNull = pemdaNull;
	}

	public List<UploadFileObj> getUploadFiles() {
		return uploadFiles;
	}

	public void setUploadFiles(List<UploadFileObj> uploadFiles) {
		this.uploadFiles = uploadFiles;
	}

	public String getIdComboYear() {
		return idComboYear;
	}

	public boolean isEditMode() {
		return editMode;
	}

	public String getUpdateYear() {
		return updateYear;
	}

	public String getIdComboPemda() {
		return idComboPemda;
	}

	public List<Pemda> getPemdas() {
		return pemdas;
	}

	public String getUpdatePemda() {
		return updatePemda;
	}

	public void onShowDialog(String ikd, String ikdNickname) {
		this.selectedIKD = ikd;
		this.selectedIkdNickname = ikdNickname;
	}

	public String getSelectedIKD() {
		return selectedIKD;
	}

	public void setSelectedIKD(String selectedIKD) {
		this.selectedIKD = selectedIKD;
	}

	public String getSelectedIkdNickname() {
		return selectedIkdNickname;
	}

	public void setSelectedIkdNickname(String selectedIkdNickname) {
		this.selectedIkdNickname = selectedIkdNickname;
	}

	public String getIdPanelYear() {
		return idPanelYear;
	}

	public String getIdPanelPemda() {
		return idPanelPemda;
	}

	public boolean isViewYear() {
		return viewYear;
	}

	public boolean isViewPemda() {
		return viewPemda;
	}

}
