package sikd.sikd5.ctrl.simpatik;

import static com.github.adminfaces.starter.util.Utils.addDetailMessage;

import java.io.ByteArrayInputStream;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import javax.naming.Context;
import javax.sound.midi.Soundbank;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import sikd.sikd5.sikd5bean.query.AmbilKontakPemdaBean;
import sikd.sikd5.sikd5bean.query.AmbilPerkiraanBelanjaBean;
import sikd.sikd5.sikd5bean.query.AmbilPosisiKasBean;
import sikd.sikd5.sikd5bean.query.Periode;
import sikd.sikd5.sikd5bean.tabel.TahunAnggaran;
import sikd.sikd5.sikd5bean.tabel.simpatik.Posisikasakunrinci;
import sikd.sikd5.sikd5bean.util.SIKDUtil;
import sikd.sikd5.sikd5bean.util.ServerUtil;
import sikd.sikd5.sikd5bean.util.SikdSessionUtil;
import sikd.sikd5.sikd5ejb.session.KontakPemdaSessionBeanRemote;
import sikd.sikd5.sikd5ejb.session.LraSessionBeanRemote;
import sikd.sikd5.sikd5ejb.session.PerkiraanBelanjaSessionBeanRemote;
import sikd.sikd5.sikd5ejb.session.PosisiKasSessionBeanRemote;
import sikd.sikd5.sikd5ejb.session.SettingsSessionBeanRemote;
import sikd.sikd5.sikd5ejb.session.login.LoginSessionBeanRemote;

/**
 * @author : agus
 * @tanggal : Feb 13, 2019
 */
@Named
@SessionScoped
public class AmbilDataSimpatik implements Serializable {
   /**
    * 
    */
   private static final long serialVersionUID = 1L;
   TahunAnggaran selectedYear = new TahunAnggaran();
   TahunAnggaran yearNull = new TahunAnggaran();
   List<TahunAnggaran> tahuns = new ArrayList<TahunAnggaran>();

   Periode selectedPeriode = new Periode();
   Periode periodeNull = new Periode();
   List<Periode> periodes = new ArrayList<Periode>();
   String kdikdSelected = "";
   Date tgAkhir = new Date();
   PosisiKasSessionBeanRemote pkSes;
   LraSessionBeanRemote lraSes;
   PerkiraanBelanjaSessionBeanRemote pbSes;
   KontakPemdaSessionBeanRemote kpSes;
   List<AmbilPosisiKasBean> posisiKass;
   List<AmbilPerkiraanBelanjaBean> perkiraanBelanjas;
   List<AmbilKontakPemdaBean> kontakPemdas;
   char SEPARATOR = ';';
   char QUOTE = '"';

   @PostConstruct
   public void init() {
      try {
         tgAkhir = new Date();
         int bulanini = tgAkhir.getMonth() + 1;
         int tahunini = tgAkhir.getYear();

         for (Periode p : SIKDUtil.getBulans()) {
            if (p.getBulanShort() == bulanini)
               selectedPeriode = p;
            periodes.add(p);

         }
         yearNull = new TahunAnggaran();
         selectedYear = new TahunAnggaran();
         Context ctxOffice = ServerUtil.getOfficeContextV3();
         SettingsSessionBeanRemote settingsSes = (SettingsSessionBeanRemote) ctxOffice
               .lookup(SikdSessionUtil.SETTINGS_SESSION);
         tahuns = settingsSes.getTahuns();
         for (TahunAnggaran t : tahuns) {
            if (t.getTahun() == (tahunini + 1900)) {
               selectedYear = t;
            }
         }
         pbSes = (PerkiraanBelanjaSessionBeanRemote) ctxOffice.lookup(SikdSessionUtil.PERKIRAAN_BELANJA_SESSION);
         pkSes = (PosisiKasSessionBeanRemote) ctxOffice.lookup(SikdSessionUtil.POSISI_KAS_SESSION);
         kpSes = (KontakPemdaSessionBeanRemote) ctxOffice.lookup(SikdSessionUtil.KONTAK_PEMDA_SESSION);
      } catch (Exception e) {
         // TODO: handle exception
         e.printStackTrace();
      }
   }

   public StreamedContent ambilData() {
      String datanya = "";
      StreamedContent file = null;
      try {
         if (kdikdSelected.equals("PKB")) {
            datanya = ambiPosisiKas();
         } else if (kdikdSelected.equals("PKS")) {
            datanya = ambiPosisiKasAkunRinci();
         } else if (kdikdSelected.equals("PBB")) {
            datanya = ambilPerkiraanBelanja();
         } else if (kdikdSelected.equals("KON")) {
            datanya = ambilKontakPemda();
         }
         
         byte[] input = datanya.getBytes();
         ByteArrayInputStream istream = new ByteArrayInputStream(input);
//         String kodeDataString = "00" + String.valueOf(kodedata + 1).trim();
//         kodeDataString = kodeDataString.substring(kodeDataString.length() - 2);
         SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
         file = new DefaultStreamedContent(istream, "text/csv", selectedYear.getTahunAsString() + kdikdSelected + sdf.format(tgAkhir) + ".csv");
         return file;
      } catch (Exception e) {
         e.printStackTrace();
//         addDetailMessage(e.getMessage());
      }
      return file;
   }

   public String ambiPosisiKas() throws Exception {
      String[] inAkun = { "1", "2", "3", "4", "5" };
//      inAkun[3]="";
      Date mulaiaimbil = new Date();
      System.out.println("Mulai ambil data : " + mulaiaimbil);
      posisiKass = pkSes.ambilPosisiKasGakRinciPerPemda(selectedYear.getTahun(), selectedPeriode.getBulanShort(), tgAkhir, inAkun);
      Date selesaiaimbil = new Date();
      System.out.println("selesaiaimbil ambil data : " + selesaiaimbil);
      StringBuilder result = new StringBuilder();
//      tahun;bulan;kdprovinsi;urprovinsi;kdpemda;kdsatker;urpemda;kdakun;urakun;nilai
      result.append("tahun").append(SEPARATOR).append("bulan").append(SEPARATOR).append("kdprovinsi").append(SEPARATOR).append("urprovinsi")
            .append(SEPARATOR).append("kdpemda").append(SEPARATOR).append("kdsatker").append(SEPARATOR);
      result.append("urpemda").append(SEPARATOR).append("kdakun").append(SEPARATOR).append("urakun").append(SEPARATOR).append("nilai").append("\n");
      DecimalFormat df = new DecimalFormat("##0.00");
      for (AmbilPosisiKasBean dt : posisiKass) {
         result.append(dt.getTahun());
         result.append(SEPARATOR);
         result.append(dt.getBulan());
         result.append(SEPARATOR);
         result.append(dt.getKdprovinsi());
         result.append(SEPARATOR);
         result.append(QUOTE);
         result.append(dt.getUrprovinsi());
         result.append(QUOTE);
         result.append(SEPARATOR);
         result.append(dt.getKdpemda());
         result.append(SEPARATOR);
         result.append(dt.getKdsatker());
         result.append(SEPARATOR);
         result.append(QUOTE);
         result.append(dt.getUrpemda());
         result.append(QUOTE);
         result.append(SEPARATOR);
         result.append(dt.getKdakun());
         result.append(SEPARATOR);
         result.append(QUOTE);
         result.append(followCVSformat(dt.getUrakun()));
         result.append(QUOTE);
         result.append(SEPARATOR);
         result.append(df.format(dt.getNilai()));
         result.append("\n");
      }
      return result.toString();
   }

   public String ambiPosisiKasAkunRinci() throws Exception {
      String[] inAkun = { "5" };
      posisiKass = pkSes.ambilPosisiKasPerPemda(selectedYear.getTahun(), selectedPeriode.getBulanShort(), tgAkhir, inAkun);
      StringBuilder result = new StringBuilder();

      result.append("tahun").append(SEPARATOR).append("bulan").append(SEPARATOR).append("kdprovinsi").append(SEPARATOR).append("urprovinsi")
            .append(SEPARATOR).append("kdpemda").append(SEPARATOR).append("kdsatker").append(SEPARATOR);
      result.append("urpemda").append(SEPARATOR).append("tahun_silpa").append(SEPARATOR).append("kdakun").append(SEPARATOR).append("urakun")
            .append(SEPARATOR).append("nilai").append("\n");
      DecimalFormat df = new DecimalFormat("##0.00");
      for (AmbilPosisiKasBean dt : posisiKass) {
         String[] pjakun = dt.getKdakun().split(Pattern.quote("."));
         if (pjakun.length > 1) {
            for (Posisikasakunrinci rinci : dt.getRincis()) {
               result.append(dt.getTahun());
               result.append(SEPARATOR);
               result.append(dt.getBulan());
               result.append(SEPARATOR);
               result.append(dt.getKdprovinsi());
               result.append(SEPARATOR);
               result.append(QUOTE);
               result.append(dt.getUrprovinsi());
               result.append(QUOTE);
               result.append(SEPARATOR);
               result.append(dt.getKdpemda());
               result.append(SEPARATOR);
               result.append(dt.getKdsatker());
               result.append(SEPARATOR);
               result.append(QUOTE);
               result.append(dt.getUrpemda());
               result.append(QUOTE);
               result.append(SEPARATOR);
               result.append(rinci.getTahun());
               result.append(SEPARATOR);
               result.append(dt.getKdakun());
               result.append(SEPARATOR);
               result.append(QUOTE);
               result.append(followCVSformat(dt.getUrakun()));
               result.append(QUOTE);
               result.append(SEPARATOR);
               result.append(df.format(rinci.getNilai()));
               result.append("\n");
            }

            result.append(dt.getTahun());
            result.append(SEPARATOR);
            result.append(dt.getBulan());
            result.append(SEPARATOR);
            result.append(dt.getKdprovinsi());
            result.append(SEPARATOR);
            result.append(QUOTE);
            result.append(dt.getUrprovinsi());
            result.append(QUOTE);
            result.append(SEPARATOR);
            result.append(dt.getKdpemda());
            result.append(SEPARATOR);
            result.append(dt.getKdsatker());
            result.append(SEPARATOR);
            result.append(QUOTE);
            result.append(dt.getUrpemda());
            result.append(QUOTE);
            result.append(SEPARATOR);
            result.append(dt.getTahun());
            result.append(SEPARATOR);
            result.append(dt.getKdakun());
            result.append(SEPARATOR);
            result.append(QUOTE);
            result.append(followCVSformat(dt.getUrakun()));
            result.append(QUOTE);
            result.append(SEPARATOR);
            result.append(df.format(dt.getNilai()));
            result.append("\n");
         }
      }
      return result.toString();
   }

   public String ambilPerkiraanBelanja() throws Exception {
      String[] inAkun = { "6", "7" };
      perkiraanBelanjas = pbSes.ambilPerkiraanBelanjaPerPemda(selectedYear.getTahun(), selectedPeriode.getBulanShort(), tgAkhir, inAkun);
      StringBuilder result = new StringBuilder();
      result.append("tahun").append(SEPARATOR).append("bulan").append(SEPARATOR).append("kdprovinsi").append(SEPARATOR).append("urprovinsi")
            .append(SEPARATOR).append("kdpemda").append(SEPARATOR).append("kdsatker").append(SEPARATOR);
      result.append("urpemda").append(SEPARATOR).append("kdakun").append(SEPARATOR).append("urakun").append(SEPARATOR).append("nilai").append("\n");
      DecimalFormat df = new DecimalFormat("##0.00");
      for (AmbilPerkiraanBelanjaBean dt : perkiraanBelanjas) {
         ambilPerkiraanBelanja0(dt, (short) 1, dt.getNilaib1(), result, df);
         ambilPerkiraanBelanja0(dt, (short) 2, dt.getNilaib2(), result, df);
         ambilPerkiraanBelanja0(dt, (short) 3, dt.getNilaib3(), result, df);
         ambilPerkiraanBelanja0(dt, (short) 4, dt.getNilaib4(), result, df);
         ambilPerkiraanBelanja0(dt, (short) 5, dt.getNilaib5(), result, df);
         ambilPerkiraanBelanja0(dt, (short) 6, dt.getNilaib6(), result, df);
         ambilPerkiraanBelanja0(dt, (short) 7, dt.getNilaib7(), result, df);
         ambilPerkiraanBelanja0(dt, (short) 8, dt.getNilaib8(), result, df);
         ambilPerkiraanBelanja0(dt, (short) 9, dt.getNilaib9(), result, df);
         ambilPerkiraanBelanja0(dt, (short) 10, dt.getNilaib10(), result, df);
         ambilPerkiraanBelanja0(dt, (short) 11, dt.getNilaib11(), result, df);
         ambilPerkiraanBelanja0(dt, (short) 12, dt.getNilaib12(), result, df);
      }
      return result.toString();
   }

   void ambilPerkiraanBelanja0(AmbilPerkiraanBelanjaBean dt, short bulan, double nilai, StringBuilder result, DecimalFormat df) {
      result.append(dt.getTahun());
      result.append(SEPARATOR);
      result.append(bulan);
      result.append(SEPARATOR);
      result.append(dt.getKdprovinsi());
      result.append(SEPARATOR);
      result.append(QUOTE);
      result.append(dt.getUrprovinsi());
      result.append(QUOTE);
      result.append(SEPARATOR);
      result.append(dt.getKdpemda());
      result.append(SEPARATOR);
      result.append(dt.getKdsatker());
      result.append(SEPARATOR);
      result.append(QUOTE);
      result.append(dt.getUrpemda());
      result.append(QUOTE);
      result.append(SEPARATOR);
      result.append(dt.getKdakun());
      result.append(SEPARATOR);
      result.append(QUOTE);
      result.append(followCVSformat(dt.getUrakun()));
      result.append(QUOTE);
      result.append(SEPARATOR);
      result.append(df.format(nilai));
      result.append("\n");

   }

   public String ambilKontakPemda() throws Exception {
//   nama1;jabatan1;hp1;email1;nama2;jabatan2;hp2;email2
      kontakPemdas = kpSes.ambilKontakPemda(selectedYear.getTahun());
      System.out.println("kontakPemdas.size() : "+kontakPemdas.size());
      StringBuilder result = new StringBuilder();
      result.append("tahun").append(SEPARATOR).append("bulan").append(SEPARATOR).append("kdprovinsi").append(SEPARATOR).append("urprovinsi")
            .append(SEPARATOR).append("kdpemda").append(SEPARATOR).append("kdsatker").append(SEPARATOR);
      result.append("urpemda").append(SEPARATOR)
            .append("nama1").append(SEPARATOR).append("jabatan1").append(SEPARATOR).append("hp1").append(SEPARATOR).append("email1").append(SEPARATOR)
            .append("nama2").append(SEPARATOR).append("jabatan2").append(SEPARATOR).append("hp2").append(SEPARATOR).append("email2").append("\n");

      for (AmbilKontakPemdaBean kn : kontakPemdas) {
         result.append(kn.getTahun());
         result.append(SEPARATOR);
         result.append(kn.getBulan());
         result.append(SEPARATOR);
         result.append(kn.getKdprovinsi());
         result.append(SEPARATOR);
         result.append(QUOTE);
         result.append(kn.getUrprovinsi());
         result.append(QUOTE);
         result.append(SEPARATOR);
         result.append(kn.getKdpemda());
         result.append(SEPARATOR);
         result.append(kn.getKdsatker());
         result.append(SEPARATOR);
         result.append(QUOTE);
         result.append(kn.getUrpemda());
         result.append(QUOTE);
         result.append(SEPARATOR);               
         result.append(QUOTE).append(followCVSformat(kn.getNama1())).append(QUOTE);
         result.append(SEPARATOR);
         result.append(QUOTE).append(followCVSformat(kn.getJabatan1())).append(QUOTE);
         result.append(SEPARATOR);
         result.append(QUOTE).append(followCVSformat(kn.getHp1())).append(QUOTE);
         result.append(SEPARATOR);
         result.append(QUOTE).append(followCVSformat(kn.getEmail1())).append(QUOTE);
         result.append(SEPARATOR);

         result.append(QUOTE).append(followCVSformat(kn.getNama2())).append(QUOTE);
         result.append(SEPARATOR);
         result.append(QUOTE).append(followCVSformat(kn.getJabatan2())).append(QUOTE);
         result.append(SEPARATOR);
         result.append(QUOTE).append(followCVSformat(kn.getHp2())).append(QUOTE);
         result.append(SEPARATOR);
         result.append(QUOTE).append(followCVSformat(kn.getEmail2())).append(QUOTE);
         result.append("\n");
      }
      return result.toString();
   }

   private static String followCVSformat(String value) {

      String result = value;
      if (result == null) {
         result = "";
      } else if (result.contains("\"")) {
         result = result.replace("\"", "\"\"");
      }
      return result;

   }

   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 Periode getSelectedPeriode() {
      return selectedPeriode;
   }

   public void setSelectedPeriode(Periode selectedPeriode) {
      this.selectedPeriode = selectedPeriode;
   }

   public List<Periode> getPeriodes() {
      return periodes;
   }

   public void setPeriodes(List<Periode> periodes) {
      this.periodes = periodes;
   }

   public String getKdikdSelected() {
      return kdikdSelected;
   }

   public void setKdikdSelected(String kdikdSelected) {
      this.kdikdSelected = kdikdSelected;
   }

   public Date getTgAkhir() {
      return tgAkhir;
   }

   public void setTgAkhir(Date tgAkhir) {
      this.tgAkhir = tgAkhir;
   }

   public Periode getPeriodeNull() {
      return periodeNull;
   }

   public void setPeriodeNull(Periode periodeNull) {
      this.periodeNull = periodeNull;
   }

}
