package sikd.sikd5.sikd5service.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.util.Date;

import javax.naming.Context;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

import sikd.sikd5.sikd5bean.fault.SIKDServiceException;
import sikd.sikd5.sikd5bean.tabel.Pemda;
import sikd.sikd5.sikd5bean.tabel.UploadFile;
import sikd.sikd5.sikd5bean.tabel.mgr.TUserAccount;
import sikd.sikd5.sikd5bean.util.SIKDUtil;
import sikd.sikd5.sikd5bean.util.ServerUtil;
import sikd.sikd5.sikd5bean.util.SikdSessionUtil;
import sikd.sikd5.sikd5bean.ws.simpatik.KontakPemda_WS;
import sikd.sikd5.sikd5bean.ws.simpatik.PerkiraanBelanja_WS;
import sikd.sikd5.sikd5bean.ws.simpatik.PosisiKas_WS;
import sikd.sikd5.sikd5ejb.session.UploadFileSessionBeanRemote;

/**
 *
 * @author Agus
 */
public class XmlSikdUtil implements Serializable {

	static JAXBContext getJaxBContext(String ikd) throws Exception {
//        if( ikd.trim().equals("ANG") ) return JAXBContext.newInstance(Apbd_WS.class);
//        else if( ikd.trim().equals("LRA") ) return JAXBContext.newInstance(RealisasiAPBD_WS.class);
//        else if( ikd.trim().equals("LAK") ) return JAXBContext.newInstance(ArusKas_WS.class);
//        else if( ikd.trim().equals("NRC") ) return JAXBContext.newInstance(Neraca_WS.class);
//        else if( ikd.trim().equals("DTH") ) return JAXBContext.newInstance(DTH_WS.class);
//        else if( ikd.trim().equals("LOP") ) return JAXBContext.newInstance(LaporanOperasional_WS.class);
//        else if( ikd.trim().equals("LPE") ) return JAXBContext.newInstance(PerubahanEkuitas_WS.class);
//        else if( ikd.trim().equals("LPS") ) return JAXBContext.newInstance(PerubahanSal_WS.class);
//        else if( ikd.trim().equals("LPD") ) return JAXBContext.newInstance(PinjamanDaerah_WS.class);
//        else if( ikd.trim().equals("PFK") ) return JAXBContext.newInstance(PerhitunganFihakKetiga_WS.class);
//        else if( ikd.trim().equals("DAG") ) return JAXBContext.newInstance(DandesApbd_WS.class);
//        else if( ikd.trim().equals("DRA") ) return JAXBContext.newInstance(DandesRealisasi_WS.class);
//        else if( ikd.trim().equals("DSD") ) return JAXBContext.newInstance(DandesSalur_WS.class);
//        else if( ikd.trim().equals("GRA") ) return JAXBContext.newInstance(GajiPnsd_WS.class);
//        else if( ikd.trim().equals("MAP") ) return JAXBContext.newInstance(MappingAkun_WS.class);
		if (ikd.trim().equals("PBB"))
			return JAXBContext.newInstance(PerkiraanBelanja_WS.class);
		else if (ikd.trim().equals("PKB"))
			return JAXBContext.newInstance(PosisiKas_WS.class);
		else if (ikd.trim().equals("KON"))
			return JAXBContext.newInstance(KontakPemda_WS.class);
		else
			return null;
	}

	@SuppressWarnings("ConvertToStringSwitch")
	static Object settingDataParsing(Unmarshaller um, String xmlFileName, String ikd) throws Exception {
		Object result = null;
//        if( ikd.trim().equals("ANG") ) {
//            result =  um.unmarshal(new StreamSource(xmlFileName), Apbd_WS.class).getValue();
//        }
//        if( ikd.trim().equals("LRA") ) {
//            result = um.unmarshal(new StreamSource(xmlFileName), RealisasiAPBD_WS.class).getValue();
//        }
//        if( ikd.trim().equals("LAK") ) {
//            result = um.unmarshal(new StreamSource(xmlFileName), ArusKas_WS.class).getValue();
//        }
//        if( ikd.trim().equals("NRC") ) {
//            result = um.unmarshal(new StreamSource(xmlFileName), Neraca_WS.class).getValue();
//        }
//        if( ikd.trim().equals("DTH") ) {
//            result =  um.unmarshal(new StreamSource(xmlFileName), DTH_WS.class).getValue();
//        }
//        if( ikd.trim().equals("LOP") ) {
//            result = um.unmarshal(new StreamSource(xmlFileName), LaporanOperasional_WS.class).getValue();
//        }
//        if( ikd.trim().equals("LPE") ) {
//            result = um.unmarshal(new StreamSource(xmlFileName), PerubahanEkuitas_WS.class).getValue();
//        }
//        if( ikd.trim().equals("LPS") ) {
//            result = um.unmarshal(new StreamSource(xmlFileName), PerubahanSal_WS.class).getValue();
//        }
//        if( ikd.trim().equals("LPD") ) {
//            result = um.unmarshal(new StreamSource(xmlFileName), PinjamanDaerah_WS.class).getValue();
//        }
//        if( ikd.trim().equals("PFK") ) {
//            result = um.unmarshal(new StreamSource(xmlFileName), PerhitunganFihakKetiga_WS.class).getValue();
//        }
//        if( ikd.trim().equals("DAG") ) {
//            result = um.unmarshal(new StreamSource(xmlFileName), DandesApbd_WS.class).getValue();
//        }
//        if( ikd.trim().equals("DRA") ) {
//            result = um.unmarshal(new StreamSource(xmlFileName), DandesRealisasi_WS.class).getValue();
//        }
//        if( ikd.trim().equals("DSD") ) {
//            result = um.unmarshal(new StreamSource(xmlFileName), DandesSalur_WS.class).getValue();
//        }
//        if( ikd.trim().equals("GRA") ) {
//            result = um.unmarshal(new StreamSource(xmlFileName), GajiPnsd_WS.class).getValue();
//        }
//        if( ikd.trim().equals("MAP") ) {
//            result = um.unmarshal(new StreamSource(xmlFileName), MappingAkun_WS.class).getValue();
//        }
		if (ikd.trim().equals("PBB")) {
			result = um.unmarshal(new StreamSource(xmlFileName), PerkiraanBelanja_WS.class).getValue();
		}
		if (ikd.trim().equals("PKB")) {
			result = um.unmarshal(new StreamSource(xmlFileName), PosisiKas_WS.class).getValue();
		}

		if (ikd.trim().equals("KON")) {
			result = um.unmarshal(new StreamSource(xmlFileName), KontakPemda_WS.class).getValue();
		}

		return result;
	}

	public static Object parsingXML(String xmlFileName, String ikd) throws Exception {
		try {
			Object hasil = null;

			JAXBContext jc = getJaxBContext(ikd);
			if (jc == null) {
				throw new Exception("Gagal parsing XML kode " + ikd + " belum didukung");
			}
			Unmarshaller um = jc.createUnmarshaller();
			hasil = settingDataParsing(um, xmlFileName, ikd);
			return hasil;
		} catch (JAXBException | SIKDServiceException ex) {
			throw new Exception("Gagal parsing XML " + ex.getMessage());
		}
	}

	public static String[] simpanExtract(String uploadPath, String kdikd, short pers, String kodeSatker, short tahun,
			byte[] berkasnya,
			String password) throws Exception {
		String per = "00" + pers;
		per = per.substring(per.length() - 2);
		String kodeikd = kdikd + per;
		try {
			String tgls = SIKDUtil.dateToString1(new Date());
			String fileName = SIKDUtil.uploadPathnya(uploadPath, tahun, kdikd) + tahun + kodeSatker.trim() + kodeikd
					+ "_" + tgls
					+ ".zip";
			String fileNamex = SIKDUtil.uploadPathUnzipnya(uploadPath, tahun, kdikd) + tahun + kodeSatker.trim()
					+ kodeikd + ".xml";
			String[] out = { fileName, fileNamex };
			File ff = new File(fileName);

			if (ff.exists()) {
				if (ff.isFile()) {
					ff.delete();
				}
			}

			File fx = new File(fileNamex);
			if (fx.exists()) {
				fx.delete();
			}
			SIKDUtil.cekFolder(SIKDUtil.uploadPathnya(uploadPath, tahun, kdikd));
			SIKDUtil.cekFolder(SIKDUtil.uploadPathUnzipnya(uploadPath, tahun, kdikd));
			FileOutputStream fos = new FileOutputStream(ff);
			fos.write(berkasnya);
			fos.flush();
			fos.close();
			UnzipFileService ufs = new UnzipFileService();
			ufs.unZipIt1(fileName, fileNamex, "xml", kodeSatker + password);
			return out;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new SIKDServiceException(e.getMessage());

		}
	}

	public static void cekBerkasZip(byte[] berkas) throws SIKDServiceException {
		String str = "";
		try {
			if (berkas == null) {
				throw new SIKDServiceException("Berkas Kosong");
			}
			if (berkas.length < 6) {
				throw new SIKDServiceException("Berkas Terlalu kecil");
			}
			for (int i = 0; i < 5; i++) {
				str = str + (char) berkas[i];
			}

			if (!str.startsWith("PK")) {
				throw new SIKDServiceException("Berkas Bukan file zip");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
//			hasil = ex.getMessage();
			throw new SIKDServiceException(ex.getMessage());
		}

	}

	public static void cekBerkasPdf(byte[] berkas) throws SIKDServiceException {
		String str = "";
		try {
			if (berkas == null) {
				throw new SIKDServiceException("Berkas Kosong");
			}
			if (berkas.length < 6) {
				throw new SIKDServiceException("Berkas Terlalu kecil");
			}
			for (int i = 0; i < 5; i++) {
				str = str + (char) berkas[i];
			}

			if (!str.startsWith("%PDF")) {
				throw new SIKDServiceException("Berkas Bukan file Pdf");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
//			hasil = ex.getMessage();
			throw new SIKDServiceException(ex.getMessage());
		}

	}

	public static String copyInsertPdf(String uploadPath, String kdikd, short pers, String kodeSatker, short tahun,
			byte[] berkasnya) throws Exception {
		String per = "00" + pers;
		per = per.substring(per.length() - 2);
		String kodeikd = kdikd + per;
		try {
			Date tgl = new Date();
			String tgls = SIKDUtil.dateToString1(tgl);
			String fileName = SIKDUtil.uploadPathHcnya(uploadPath, tahun, kdikd) + tahun + kodeSatker.trim() + kodeikd
					+ "_" + tgls
					+ ".pdf";

			File ff = new File(fileName);

			if (ff.exists()) {
				if (ff.isFile()) {
					ff.delete();
				}
			}

			SIKDUtil.cekFolder(SIKDUtil.uploadPathHcnya(uploadPath, tahun, kdikd));
			FileOutputStream fos = new FileOutputStream(ff);
			fos.write(berkasnya);
			fos.flush();
			fos.close();
			Context ctxOffice = ServerUtil.getOfficeContextV3();
			UploadFileSessionBeanRemote session = (UploadFileSessionBeanRemote) ctxOffice
					.lookup(SikdSessionUtil.UPLOAD_FILE_SESSION);
			UploadFile uf = new UploadFile(tahun, "pdf", kodeSatker, fileName, tgl, kodeikd);
			session.insert(uf);
			return fileName;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new SIKDServiceException(e.getMessage());

		}
	}

	public static void cekLoginService(String kodeSatker, String kodePemda, String userName, String password,
			TUserAccount tuserAccount)
			throws Exception {
//		System.out.println(tuserAccount);
		if (tuserAccount == null) {
			throw new SIKDServiceException("Username tidak terdaftar");
		}
		if (!tuserAccount.isActives()) {
			throw new SIKDServiceException("Username di suspend");
		}
		String pp = "";
		for (int i = 0; i < tuserAccount.getPassword().length; i++) {
			pp = pp + tuserAccount.getPassword()[i];
		}
		if (!pp.equals(password)) {
			throw new SIKDServiceException("001", "Password Salah");
		}
		if (tuserAccount.getPemda() != null) {
			if (kodeSatker.equals(tuserAccount.getPemda().getKodeSatker())) {
				if (kodePemda.equals(tuserAccount.getPemda().getKodePemda5Digit())) {
					return;
				} else {
					throw new SIKDServiceException("Kode Pemda " + kodePemda + " tidak terdaftar");
				}
			}
		}
		if (tuserAccount.getWilayah() != null) {
			if (tuserAccount.getWilayah().getPemdas() != null) {
				Pemda pemdanya = null;
				for (Pemda p : tuserAccount.getWilayah().getPemdas()) {
					if (kodeSatker.equals(p.getKodeSatker())) {
						pemdanya = p;
						break;
					}
				}
				if (pemdanya != null) {
					if (kodePemda.equals(pemdanya.getKodePemda5Digit())) {
						return;
					} else {
						throw new SIKDServiceException("Kode Pemda " + kodePemda + " tidak terdaftar");
					}
				}

			}
		}
		throw new SIKDServiceException(
				"Tidak berhak upload Kode Satker " + kodeSatker + " atau Kode Satker tersebut tidak terdaftar");
	}
	
	public static void cekParamSimpatik(String kodeSatker, String kodePemda, short tahun,short bulan,
			String userName, String password)	throws Exception {
		if (kodeSatker == null || kodeSatker.equals("")) {
			throw new SIKDServiceException("kodeSatker tidak boleh kosong");
		}
		if (kodePemda == null || kodePemda.equals("")) {
			throw new SIKDServiceException("kodePemda tidak boleh kosong");
		}
		if (tahun<1) {
			throw new SIKDServiceException("tahun tidak boleh kosong");
		}
		if (bulan<1 || bulan > 12) {
			throw new SIKDServiceException("bulan tidak boleh kosong dan tidak lebih dari 12");
		}
	}
}
