/*
 * 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.sikd5.sikd5ejb.session;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import sikd.sikd5.sikd5bean.fault.SIKDServiceException;
import sikd.sikd5.sikd5bean.query.AmbilKontakPemdaBean;
import sikd.sikd5.sikd5bean.query.InfoPengiriman;
import sikd.sikd5.sikd5bean.ws.simpatik.KontakPemda_WS;
import sikd.sikd5.sikd5ejb.dao.KontakPemdaDao;
import sikd.sikd5.sikd5ejb.session.util.MyBatisConnectionFactory;

@Stateless
@Remote({ KontakPemdaSessionBeanRemote.class })
public class KontakPemdaSessionBean implements KontakPemdaSessionBeanRemote {

   private SqlSessionFactory sqlSessionFactory;
   private SqlSession session = null;
   KontakPemdaDao dao;

   @PostConstruct
   public void init() {
      try {
         sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory();
         dao = new KontakPemdaDao();
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }

   @Override
   public String getInfoPengiriman(String kodeSatker, short tahun, short bulan) throws Exception {
      InfoPengiriman info = new InfoPengiriman();
      try {
         session = sqlSessionFactory.openSession();
         info = dao.getInfoPengiriman(kodeSatker, tahun, bulan, session);
      } catch (Exception e) {
         throw new SIKDServiceException(e.getMessage());
      } finally {
         session.close();
      }
      return info.getInfoString();
   }

   @Override
   public long insert(KontakPemda_WS kontakPemda, String nmfile) throws Exception {
      long hasil = 0;
      try {
         if (kontakPemda == null) {
            throw new SIKDServiceException("Data Kontak Pemda Kosong");
         }
         session = sqlSessionFactory.openSession();
         hasil = dao.insert(kontakPemda, nmfile, session);
         session.commit();
      } catch (Exception e) {
         session.rollback();
         throw new SIKDServiceException(e.getMessage());

      } finally {
         session.close();
      }
      return hasil;
   }

   @Override
   public List<AmbilKontakPemdaBean> ambilKontakPemda(short tahun) throws Exception {
      List<AmbilKontakPemdaBean> hasil = new ArrayList<>();
      try {

         session = sqlSessionFactory.openSession();
         hasil = dao.ambilKontakPemda(tahun, session);
      } catch (Exception e) {
         throw new SIKDServiceException(e.getMessage());

      } finally {
         session.close();
      }
      return hasil;
   }

}
