/*
 * CPVCodeManager.java
 *
 * Created on 4  2007, 1:30 ��
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.ellectra.session;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.Vector;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.transaction.UserTransaction;
import org.ellectra.entity.CPVCodesEntity;

/**
 *
 * @author tdi
 */
@WebService()
@Stateless
public class CPVCodeManager {
    
    //declare a persistence manager factory, we will use it
    //to get a entity manager
    @PersistenceUnit
    private EntityManagerFactory emf;
    
    //declare a transaction manager
    //transactions are used when we do add or edit
    //@Resource 
    //private UserTransaction utx;
    
    protected BufferedReader in;
    
    
     public String UpdateCPVFromCSVFile(String szPath,String szLang) 
    {
        return LoadFileCC(szPath,szLang);
    }
    
    
    
    
    private String LoadFileCC(String szPath,String szLang) 
    {
        
      //  int iloop=0;
        String szCodes="";
        String F1="";
        String F2="";
        try {
            
            in = new BufferedReader(new FileReader(szPath));
        
            String record1 = null; 
            Vector<String> fields=null;
            try { 

               while ( (record1=in.readLine()) != null ) { 
        //            iloop=iloop+1;   
                    
                    //look to found f1 and f2
                    
                    int j = record1.indexOf(";", 0);
                    
                    F1=record1.substring(0,j);
                    F2=record1.substring(j+1,record1.length());
                    
                    
                    
          //          if (iloop>2 )
            //        {
                   // return  AddCode(F1,F2);
                        
                        try { // Call Web Service Operation
                            
                            // TODO process result here
                            AddCode(F1, F2,szLang);
                            //System.out.println("Result = "+result);
                        } catch (Exception ex) {
                            // TODO handle custom exceptions here
                        }     
               //     }
                 
               } 

            } catch (IOException e) { 
               return "Error on read File";
            }  
        } catch (FileNotFoundException ex) {
            return "Error on Open File";
        }
        try {
            in.close();
        } catch (IOException ex) {
            return "Error on Close File";
        }
        return "OK";
    }
    /**
     *Get All users already in the database
     *Returns : List type of UserAccount
     */
     public List<CPVCodesEntity> GetAllCPVCodes(String szlang) {
        assert emf != null;  //Make sure injection went through correctly.
        EntityManager em = null;
        em = emf.createEntityManager();
        return em.createQuery("select c from CPVCodesEntity c where c.Languagecpv=:uv").setParameter("uv",szlang).getResultList();
    }
    
     /**
     *Get All users already in the database
     *Returns : List type of UserAccount
      *where u.Username=:Uservar").setParameter("Uservar",szUsername).getResultList();
     */
     public List<CPVCodesEntity> GetDetailsForCode(String szCode,String szlang) {
        assert emf != null;  //Make sure injection went through correctly.
        EntityManager em = null;
        em = emf.createEntityManager();
        return em.createQuery("select c from CPVCodesEntity c where c.CPVCODE=:Uservar and c.Languagecpv=:uv").setParameter("Uservar",szCode).setParameter("uv",szlang).getResultList();
    }
     
    /**
     *Get selected user from the database
     *Parameter : username type of string
     *Returns: List type of userAccount
     */
    public List<CPVCodesEntity> SearchForCPVCodes(String szCode,String szlang)
    {
        assert emf != null;  //Make sure injection went through correctly.
        String szQuery="select c from CPVCodesEntity c where c.Description LIKE '%"+szCode+"%' and c.Languagecpv='"+szlang+"'";//%"+szCode+"%";
        EntityManager em = null;
        em = emf.createEntityManager();
        return em.createQuery(szQuery).getResultList();
        
    }
    
    /**
     *Add a new user in the database
     *Parameters : user Fields
     *Return a string with the message
     */
    public String AddCode(String CPVCode,String CpvDesc,String szLang)
    {
            EntityManager em = null;
            em = emf.createEntityManager();
            
            
                CPVCodesEntity pCPVCode;
                pCPVCode = new CPVCodesEntity();

                pCPVCode.setCPVCODE(CPVCode);
                pCPVCode.setDescription(CpvDesc);
                pCPVCode.setLanguagecpv(szLang);
                
                
                try {
      //              utx.begin();
                    em.persist(pCPVCode);
        //            utx.commit();
                    return "CPV Code Added";
                } catch (Exception e) {               

                    return "Error on Add CPV Code - Platform Error"+e.getLocalizedMessage();
                }
            
    }
            
    public String DeleteCodeForLang(String szlang)
    {
        assert emf != null;  //Make sure injection went through correctly.
        EntityManager em = null;
        em = emf.createEntityManager();
        List<CPVCodesEntity> dList= em.createQuery("select c from CPVCodesEntity c where c.Languagecpv=:uv").setParameter("uv",szlang).getResultList();
        for (int i=0;i<dList.size();i++)
        {
            CPVCodesEntity deleted = (CPVCodesEntity)dList.get(i);
            em.remove(deleted);
        }
        return "success";
    }
    
    /**
     *Private function to check if user exists
     *Parameters : username type of string
     *Return : true or false
     */
    private Boolean IsCPVCodeExists(String szCode)
    {
        assert emf != null;  //Make sure injection went through correctly.
                
        EntityManager em = null;
        try {
            em = emf.createEntityManager();
       

            String sQuery="select c from CPVCodesEntity c where c.CPVCODE=:Uservar";
            List codes = em.createQuery(sQuery).setParameter("Uservar",szCode).getResultList();
            if (codes.isEmpty()==true)
            {
                em.close();
                return false;
            }
            else
            {
                return true;
            }
        } catch (Exception ex) {
            
            return false;
        } 
    }
}
