package com.bizofficer.admin.topiccontent;



import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.TypedQuery;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.crossstore.ChangeSetPersister.NotFoundException;
import org.springframework.stereotype.Service;

import com.bizofficer.hibernate.entity.PgprepAdministrator;
import com.bizofficer.hibernate.entity.PgprepTopicContent;
import com.bizofficer.hibernate.repository.PgprepAdministratorRepository;
import com.bizofficer.module.util.PrivilegesBeans;
import com.bizofficer.module.util.PrivilegesUtil;
import com.bizofficer.module.util.RoleModules;
import com.bizofficer.system.util.MakeDate;


@Service
public class ContentAdService{
	
	private static final Logger logger = Logger.getLogger(ContentAdService.class);
	
	@Autowired
	EntityManagerFactory entityManagerFactory;
	
	@Autowired
	PgprepAdministratorRepository adminRepo;
	
	public Object execute(Object obj) throws NotFoundException{
		ContentAdBean objBean = (ContentAdBean) obj;
		ContentAdResponseBean responseObj = new ContentAdResponseBean();
		
		try {
			
			responseObj.setResponseTxt("failed");
			
			logger.info("LoginEmailId >> " + objBean.getLoginEmailId() );
			logger.info("Token >> " + objBean.getToken() );
			logger.info("Keyword >> " + objBean.getKeyword() );
			
			if(objBean.getLoginEmailId()==null || objBean.getToken()==null) {
				return responseObj;
			}
			
			PgprepAdministrator adminObj = (PgprepAdministrator) adminRepo.findByEmailIdAndLoginToken(objBean.getLoginEmailId(), objBean.getToken());
			if(adminObj==null) {
				return responseObj;
			}
			logger.info("Verify >> " + adminObj.getId() );
			if(adminObj.getUserType()==0 && adminObj.getRoleId()!=null && adminObj.getPrivileges()!=null){				
				PrivilegesUtil	myPgUtil = new PrivilegesUtil();
				PrivilegesBeans prvgbnObj = myPgUtil.authPrivileges(adminObj.getPrivileges(), RoleModules.getSmartLearningTopic() );
				logger.info(prvgbnObj.toString());
				if(prvgbnObj!=null && prvgbnObj.getView()!=null && prvgbnObj.getView()==1) {					
					responseObj.setPrivileges(prvgbnObj);
				}else {
					logger.info("NoAuthorization");
					responseObj.setResponseTxt("NoAuthorization");
					return responseObj;
				}
			}else {
				PrivilegesUtil	myPgUtil = new PrivilegesUtil();
				PrivilegesBeans prvgbnObj = myPgUtil.fullPrivileges();
				responseObj.setPrivileges(prvgbnObj);
			}
			
			MakeDate mkdateObj = new MakeDate();
			List<StudyContentsAdminBean> subsList = new ArrayList<StudyContentsAdminBean>();
			
			EntityManager entityManager = entityManagerFactory.createEntityManager();
			entityManager.getTransaction().begin();
			
			String whereQry =" WHERE 1=1 ";			
			if(objBean.getKeyword()!=null && objBean.getKeyword().length()>0 ) {
				whereQry +=" AND (contentName LIKE :keyword OR topicName LIKE :keyword) ";
			}
			
			TypedQuery<PgprepTopicContent> query = (TypedQuery<PgprepTopicContent>) entityManager.createQuery("from "+PgprepTopicContent.class.getName()+whereQry+" order by id desc ", PgprepTopicContent.class);
			if(objBean.getKeyword()!=null && objBean.getKeyword().length()>0 ) {
				query.setParameter("keyword", "%"+objBean.getKeyword()+"%");
			}
			query.setFirstResult(0);
			query.setMaxResults(500);
			List<?> resultListCat = query.getResultList();
			Iterator<?> iteratorCat=resultListCat.iterator();	
			StudyContentsAdminBean subObj;
			int i=1;
			while(iteratorCat.hasNext()){
				PgprepTopicContent myObj = (PgprepTopicContent)iteratorCat.next();		
				
				subObj = new StudyContentsAdminBean();
				
				subObj.setId(i);
				subObj.setAutoId(myObj.getId());
				subObj.setTopicId(myObj.getTopicId());
				subObj.setTopicName(myObj.getTopicName());
				subObj.setContOrder(myObj.getContOrder());
				subObj.setContentName(myObj.getContentName());
				subObj.setContentUrl(myObj.getContentUrl());
				subObj.setCountry(myObj.getCountry());
				subObj.setStandard(myObj.getStandard());
				subObj.setPostBy(myObj.getPostBy());
				
				if(myObj.getContentType()!=null && myObj.getContentType()==1) {
					subObj.setContentType("Video");
				}else if(myObj.getContentType()!=null && myObj.getContentType()==2) {
					subObj.setContentType("PDF");
				}else if(myObj.getContentType()!=null && myObj.getContentType()==3) {
					subObj.setContentType("PPT");	
				}else {
					subObj.setContentType("Text");
					subObj.setDescription(myObj.getDescription());
				}
				
				if(myObj.getContentSource()!=null && myObj.getContentSource()==1) {
					subObj.setContentSource("URL");
				}else if(myObj.getContentSource()!=null && myObj.getContentSource()==2) {
					subObj.setContentSource("Text");	
				}else {
					subObj.setContentSource("File");
				}
				
				if(myObj.getPostDate()!=null) {
					subObj.setPostDate(mkdateObj.dateToString(myObj.getPostDate(), "dd-MM-yyyy") );
				}

				subObj.setCurrentSource(myObj.getContentSource());
				
				if(myObj.getContentSource()!=null && myObj.getContentSource()==3 && myObj.getContentUrl()!=null && myObj.getContentUrl().length()>0) {
					String[] urlArr = myObj.getContentUrl().split("/");
					String fileName = urlArr[urlArr.length-1];
					subObj.setCurrentFile(fileName);
				}
				
				subsList.add(subObj);
				i++;
			}

			responseObj.setList(subsList);			
				
			entityManager.getTransaction().commit();
			entityManager.close();
			
			responseObj.setResponseTxt("success");
		        
		}catch(Exception e) {
			e.getStackTrace();
		}
		
		
		return responseObj;
	}
	

	
	

	
	
}
