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.tabel.Pemda;
import sikd.sikd5.sikd5bean.tabel.TahunAnggaran;
import sikd.sikd5.sikd5ejb.dao.SettingsDao;
import sikd.sikd5.sikd5ejb.session.util.MyBatisConnectionFactory;

/**
 * Session Bean implementation class SettingsSessionBean
 */
@Stateless
@Remote(SettingsSessionBeanRemote.class)
public class SettingsSessionBean implements SettingsSessionBeanRemote {

	/**
	 * Default constructor.
	 */
	public SettingsSessionBean() {
		
	}

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

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

	/**
	 * @see SettingsSessionBeanRemote#getTahuns()
	 */
	public List<TahunAnggaran> getTahuns() throws Exception {
		List<TahunAnggaran> hasil = new ArrayList<>();
		try {
			session = sqlSessionFactory.openSession();
			hasil = dao.getTahuns(session);

		} catch (Exception e) {
			throw new SIKDServiceException(e.getMessage());

		} finally {
			if (session != null) {
			session.close();
			}
		}
		return hasil;
	}

	@Override
	public List<Pemda> getProvByTahuns(short tahun) throws Exception {
		List<Pemda> hasil = new ArrayList<Pemda>();
		try {
			session = sqlSessionFactory.openSession();
			hasil = dao.getProvByTahuns(tahun, session);

		} catch (Exception e) {
			throw new SIKDServiceException(e.getMessage());

		} finally {
			if (session != null) {
			session.close();
			}
		}
		return hasil;
	}

	@Override
	public List<Pemda> getPemdaByTahuns(short tahun) throws Exception {
		List<Pemda> hasil = new ArrayList<Pemda>();
		try {
			session = sqlSessionFactory.openSession();
			hasil = dao.getPemdaByTahuns(tahun, session);

		} catch (Exception e) {
			throw new SIKDServiceException(e.getMessage());

		} finally {
			if (session != null) {
			session.close();
			}
		}
		return hasil;
	}

}
