package sikd.sikd5.sikd5ejb.dao.ref;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.ibatis.session.SqlSession;
import sikd.sikd5.sikd5bean.fault.SIKDServiceException;
import sikd.sikd5.sikd5bean.util.SIKDUtil;
import sikd.sikd5.sikd5bean.ws.ref.VersiAplikasi_WS;
import sikd.sikd5.sikd5ejb.mapper.ref.VersiMapper;

/**
 *
 * @author soraturaes
 */
public class VersiDao {

    public VersiAplikasi_WS getVersiAplikasi(String kodesatker, String ip, Date tanggalclient, String namaaplikasi, String versiaplikasi, SqlSession session) throws SIKDServiceException {
        VersiAplikasi_WS hasil;
        Date dd = new Date();
        VersiMapper versiMapper = session.getMapper(VersiMapper.class);
        String ket = "";
        hasil = versiMapper.getVersiAplikasi(namaaplikasi);
        if (hasil != null && hasil.getVersi() != null && !hasil.getVersi().trim().equals("")) {
            int versiClient = SIKDUtil.versiStringToInt(versiaplikasi);
            int versiDB = SIKDUtil.versiStringToInt(hasil.getVersi());
            if( versiClient < versiDB ){
                String fileName = versiMapper.getAplikasiFile(namaaplikasi);
                try {
                    File ff = new File(fileName);
                    byte[] bb = new byte[(int) ff.length()];
                    FileInputStream fis = new FileInputStream(ff);
                    for (int i = 0; i < bb.length; i++) {
                        bb[i] = (byte) fis.read();
                    }
                    hasil.setFilenya(bb);
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(VersiDao.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(VersiDao.class.getName()).log(Level.SEVERE, null, ex);
                }
                
                ket = versiClient+"";
            }
            else{
                hasil.setFilenya(null);
                ket = "Versi Sudah Terbaru";
            }
        }
        
        Long id = versiMapper.selectLogCekVersiId(kodesatker, ip, dd, namaaplikasi);
        if (id == null || id == 0) {
        	versiMapper.insertLogCekVersi(kodesatker, ip, dd, namaaplikasi, new Timestamp(dd.getTime()), new Timestamp(tanggalclient.getTime()), versiaplikasi, ket);    
        } else {
        	versiMapper.updateCekLogVersiByPrimaryKey(id, new Timestamp(dd.getTime()), new Timestamp(tanggalclient.getTime()), versiaplikasi, ket);
        }

        return hasil;
    }

}
