package com.bizofficer.admin.cache;



import java.sql.Connection;
import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.TypedQuery;
import javax.sql.DataSource;

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.apiweb.keywords.CoursesKeywordBean;
import com.bizofficer.apiweb.keywords.KeywordBean;
import com.bizofficer.apiweb.keywords.KeywordService;
import com.bizofficer.apiweb.keywords.LearningKeywordService;
import com.bizofficer.apiweb.mocktestlist.BeanMT;
import com.bizofficer.apiweb.mocktestlist.MockTestListBean;
import com.bizofficer.apiweb.mocktestlist.MockTestListService;
import com.bizofficer.apiweb.studymaterials.BeanTC;
import com.bizofficer.apiweb.studymaterials.TopicContentService;
import com.bizofficer.apiweb.topics.CoursesTopicBean;
import com.bizofficer.apiweb.topics.LearningTopicsService;
import com.bizofficer.apiweb.topics.TopicBean;
import com.bizofficer.apiweb.topics.TopicService;
import com.bizofficer.apiweb.topics.TopicTestTopicsService;
import com.bizofficer.apiweb.treeview.LearningTreeviewPageService;
import com.bizofficer.apiweb.treeview.TopicTestTreeviewPageService;
import com.bizofficer.apiweb.treeview.TreeviewBean;
import com.bizofficer.apiweb.treeview.TreeviewPageBean;
import com.bizofficer.apiweb.treeview.TreeviewPageService;
import com.bizofficer.hibernate.entity.PgprepCacheTemplate;
import com.bizofficer.hibernate.entity.TemplateManagement;
import com.bizofficer.hibernate.repository.PgprepCacheTemplateRepository;
import com.bizofficer.pojo.response.ListResponsePojo;
import com.bizofficer.util.module.MysqlTableNames;
import com.bizofficer.util.system.MakeDate;
import com.google.gson.Gson;



@Service
public class CacheTempAdmService{
	
	private static final Logger logger = Logger.getLogger(CacheTempAdmService.class);
	
	@Autowired
    DataSource appDataSource;
    
	@Autowired
	EntityManagerFactory entityManagerFactory;
	
	@Autowired
	PgprepCacheTemplateRepository cacheOrgRepo;
	
	@Autowired
	private TopicService topicServiceObj;
	
	@Autowired
	private KeywordService keywordServiceObj;
	
	@Autowired
	private TreeviewPageService treeviewPageServiceObj;
	
	@Autowired
	private LearningTreeviewPageService learningTreeviewPageServiceObj;
	
	@Autowired
	private TopicTestTreeviewPageService topicTestTreeviewPageServiceObj;
	
	@Autowired
	private LearningTopicsService learningTopicsServiceObj;
	
	@Autowired
	private TopicTestTopicsService topicTestTopicsServiceObj;
	
	@Autowired
	private LearningKeywordService learningKeywordServiceObj;
	
	@Autowired
	private TopicContentService topicContentServiceObj;
	
	@Autowired
	private MockTestListService mockTestListServiceObj;

	
	public Object execute(Object obj) throws NotFoundException{
		TQCAdminBean objBean = (TQCAdminBean) obj;
		TQCAdminResponseBean loginResponseBeanObj = new TQCAdminResponseBean();
		
		try {

			logger.info("**********************************************************************");
			logger.info("**** TEMPLATE CACHE STARTING ");
			logger.info("**********************************************************************");
			
			String whereSQL=" ORDER BY templateId  ";
			if(objBean.getTemplateId()!=null && objBean.getTemplateId()>0) {
				whereSQL=" AND templateId=:templateId ";
			}else {
				Connection conn = appDataSource.getConnection();
	            if (conn != null) {
                	conn.createStatement().execute("TRUNCATE TABLE "+MysqlTableNames.getPgprepCacheTemplate());
	            }   	
	            conn.close();
			}

			Gson gson = new Gson();
			MakeDate dateObj = new MakeDate();
			EntityManager entityManager = entityManagerFactory.createEntityManager();
			entityManager.getTransaction().begin();

			Integer cacheUpdate = 0;
			if(objBean.getTemplateId()!=null && objBean.getTemplateId()>0) {
				TypedQuery<PgprepCacheTemplate> querySCT = (TypedQuery<PgprepCacheTemplate>) entityManager.createQuery("from "+PgprepCacheTemplate.class.getName()+" where templateId=:templateId ", PgprepCacheTemplate.class);
				querySCT.setParameter("templateId", objBean.getTemplateId());
				querySCT.setFirstResult(0);
				querySCT.setMaxResults(1);
				List<?> resultListSCT = querySCT.getResultList();
				Iterator<?> iteratorSCT=resultListSCT.iterator();
				if(iteratorSCT.hasNext()) {
					PgprepCacheTemplate myObjFound = (PgprepCacheTemplate)iteratorSCT.next();
					cacheUpdate = myObjFound.getId();
				}	
			}
			
			TypedQuery<TemplateManagement> query = (TypedQuery<TemplateManagement>) entityManager.createQuery("from "+TemplateManagement.class.getName()+" where 1=1 "+whereSQL, TemplateManagement.class);
			if(objBean.getTemplateId()!=null && objBean.getTemplateId()>0) {
				query.setParameter("templateId", objBean.getTemplateId());
				query.setFirstResult(0);
				query.setMaxResults(1);
			}
			List<?> resultList = query.getResultList();
			Iterator<?> iterator=resultList.iterator();
			while(iterator.hasNext()){
				TemplateManagement myObj = (TemplateManagement)iterator.next();			

				logger.info("TemplateId: "+myObj.getTemplateId());
				
				PgprepCacheTemplate cacheOrgObj;
				if(cacheUpdate>0) {
					cacheOrgObj = (PgprepCacheTemplate)entityManager.find(PgprepCacheTemplate.class, cacheUpdate);
				}else {
					cacheOrgObj = new PgprepCacheTemplate();
				}
				
				cacheOrgObj.setTemplateId(myObj.getTemplateId());
				cacheOrgObj.setUpdatedDate(dateObj.getCurrentTimeStamp());
				
				if(myObj.getTemplateId()>0) {

						logger.info("**********************************************************************");
						logger.info("*************** TOPIC TREEVIEW  ***********************************");
						logger.info("**********************************************************************");
						logger.info("Topic Treeview TemplateId: "+myObj.getTemplateId());
						TreeviewBean treeviewBean = new TreeviewBean();
						treeviewBean.setTemplateId(myObj.getTemplateId());
						@SuppressWarnings("unchecked")
						List<TreeviewPageBean> treeviewPageList = (List<TreeviewPageBean>) (Object) treeviewPageServiceObj.doExecute(treeviewBean);
						if(treeviewPageList!=null && treeviewPageList.size()>0) {
							logger.info("Template ("+myObj.getTemplateId()+") Total Topics in Treeview: "+treeviewPageList.size());
							cacheOrgObj.setTopicTree(gson.toJson(treeviewPageList));
						}else {
							logger.info("No Topic Treeview Found for template: "+myObj.getTemplateId());
							
						}
						

						logger.info("**********************************************************************");
						logger.info("*************** TOPIC TREEVIEW LEARNING  ***********************************");
						logger.info("**********************************************************************");
						logger.info("Topic Treeview Learning TemplateId: "+myObj.getTemplateId());
						TreeviewBean treeviewLearningBean = new TreeviewBean();
						treeviewLearningBean.setTemplateId(myObj.getTemplateId());
						@SuppressWarnings("unchecked")
						List<TreeviewPageBean> treeviewLearningList = (List<TreeviewPageBean>) (Object) learningTreeviewPageServiceObj.doExecute(treeviewLearningBean);
						if(treeviewLearningList!=null && treeviewLearningList.size()>0) {
							logger.info("Template ("+myObj.getTemplateId()+") Total Topics LEARNING in Treeview: "+treeviewLearningList.size());
							cacheOrgObj.setTopicTreeLearning(gson.toJson(treeviewLearningList));
						}else {
							logger.info("No Topic Treeview LEARNING Found for template: "+myObj.getTemplateId());
							
						}

						
						logger.info("**********************************************************************");
						logger.info("*************** TOPIC TREEVIEW TEST  ***********************************");
						logger.info("**********************************************************************");
						logger.info("Topic Treeview TEST TemplateId: "+myObj.getTemplateId());
						TreeviewBean treeviewTestBean = new TreeviewBean();
						treeviewTestBean.setTemplateId(myObj.getTemplateId());
						@SuppressWarnings("unchecked")
						List<TreeviewPageBean> treeviewTestList = (List<TreeviewPageBean>) (Object) topicTestTreeviewPageServiceObj.doExecute(treeviewTestBean);
						if(treeviewTestList!=null && treeviewTestList.size()>0) {
							logger.info("Template ("+myObj.getTemplateId()+") Total Topics TEST in Treeview: "+treeviewTestList.size());
							cacheOrgObj.setTopicTreeTest(gson.toJson(treeviewTestList));
						}else {
							logger.info("No Topic Treeview TEST Found for template: "+myObj.getTemplateId());
							
						}

						
						logger.info("**********************************************************************");
						logger.info("*************** TOPIC LIST  ***********************************");
						logger.info("**********************************************************************");
						TopicBean topicBean = new TopicBean();
						topicBean.setTemplateId(myObj.getTemplateId());
						@SuppressWarnings("unchecked")
						List<CoursesTopicBean> coursesTopicList = (List<CoursesTopicBean>) (Object) topicServiceObj.doExecute(topicBean);
						if(coursesTopicList!=null && coursesTopicList.size()>0) {
							logger.info("Template ("+myObj.getTemplateId()+") Total Topics: "+coursesTopicList.size());
							cacheOrgObj.setTopicList(gson.toJson(coursesTopicList));
							
						}else {
							logger.info("No Topic Found for template: "+myObj.getTemplateId());
							
						}
						

						logger.info("**********************************************************************");
						logger.info("*************** TOPIC LIST LEARNING  ***********************************");
						logger.info("**********************************************************************");
						TopicBean topicBnLearningBean = new TopicBean();
						topicBnLearningBean.setTemplateId(myObj.getTemplateId());
						@SuppressWarnings("unchecked")
						List<CoursesTopicBean> coursesTopicListLearning = (List<CoursesTopicBean>) (Object) learningTopicsServiceObj.doExecute(topicBnLearningBean);
						if(coursesTopicListLearning!=null && coursesTopicListLearning.size()>0) {
							logger.info("Template ("+myObj.getTemplateId()+") Total Topics: "+coursesTopicListLearning.size());
							cacheOrgObj.setTopicListLearning(gson.toJson(coursesTopicListLearning));
							
						}else {
							logger.info("No TOPIC LIST LEARNING Found for template: "+myObj.getTemplateId());
							
						}


						logger.info("**********************************************************************");
						logger.info("*************** TOPIC LIST TEST  ***********************************");
						logger.info("**********************************************************************");
						TopicBean topicBnTestBean = new TopicBean();
						topicBnTestBean.setTemplateId(myObj.getTemplateId());
						@SuppressWarnings("unchecked")
						List<CoursesTopicBean> coursesTopicListTest = (List<CoursesTopicBean>) (Object) topicTestTopicsServiceObj.doExecute(topicBnTestBean);
						if(coursesTopicListTest!=null && coursesTopicListTest.size()>0) {
							logger.info("Template ("+myObj.getTemplateId()+") Total Topics: "+coursesTopicListTest.size());
							cacheOrgObj.setTopicListTest(gson.toJson(coursesTopicListTest));
							
						}else {
							logger.info("No TOPIC LIST TEST Found for template: "+myObj.getTemplateId());
							
						}

						
						
						logger.info("**********************************************************************");
						logger.info("*************** KEYWORD LIST  ***********************************");
						logger.info("**********************************************************************");
						logger.info("Keywords List TemplateId: "+myObj.getTemplateId());
						KeywordBean keywordBean = new KeywordBean();
						keywordBean.setTemplateId(myObj.getTemplateId());
						@SuppressWarnings("unchecked")
						List<CoursesKeywordBean> coursesKeywordList = (List<CoursesKeywordBean>) (Object) keywordServiceObj.doExecute(keywordBean);
						if(coursesKeywordList!=null && coursesKeywordList.size()>0) {
							logger.info("Template ("+myObj.getTemplateId()+") Total Keywords: "+coursesKeywordList.size());
							cacheOrgObj.setKeywordList(gson.toJson(coursesKeywordList));
						}else {
							logger.info("No Keyword Found for template: "+myObj.getTemplateId());
							
						}
						
						
						logger.info("**********************************************************************");
						logger.info("*************** KEYWORD LIST LEARNING ***********************************");
						logger.info("**********************************************************************");
						logger.info("Keywords List LEARNING TemplateId: "+myObj.getTemplateId());
						KeywordBean keywordBeanLearning = new KeywordBean();
						keywordBeanLearning.setTemplateId(myObj.getTemplateId());
						@SuppressWarnings("unchecked")
						List<CoursesKeywordBean> coursesKeywordListLearning = (List<CoursesKeywordBean>) (Object) learningKeywordServiceObj.doExecute(keywordBeanLearning);
						if(coursesKeywordListLearning!=null && coursesKeywordListLearning.size()>0) {
							logger.info("Template ("+myObj.getTemplateId()+") Total Learning Keywords: "+coursesKeywordListLearning.size());
							cacheOrgObj.setKeywordListLearning(gson.toJson(coursesKeywordListLearning));
						}else {
							logger.info("No Learning Keyword Found for template: "+myObj.getTemplateId());
							
						}
					
						logger.info("**********************************************************************");
						logger.info("*************** SMART LEARNING ***********************************");
						logger.info("**********************************************************************");
						logger.info("SMART LEARNING TemplateId: "+myObj.getTemplateId());
						BeanTC beanTC = new BeanTC();
						beanTC.setTemplateId(myObj.getTemplateId());						
						ListResponsePojo responseObj = (ListResponsePojo) (Object) topicContentServiceObj.doExecute(beanTC);
						logger.info("SMART LEARNING ResponseTxt: "+responseObj.getResponseTxt());
						if("success".equals(responseObj.getResponseTxt())) {
							logger.info("Template ("+myObj.getTemplateId()+") Total SMART LEARNING: "+responseObj.getList().size());
							cacheOrgObj.setSmartLearning(gson.toJson(responseObj.getList()));
						}else {
							logger.info("No SMART LEARNING Found for template: "+myObj.getTemplateId());
							
						}
						
						
						logger.info("**********************************************************************");
						logger.info("*************** MOCK TEST ***********************************");
						logger.info("**********************************************************************");
						logger.info("MOCK TEST TemplateId: "+myObj.getTemplateId());
						BeanMT beanMT = new BeanMT();
						beanMT.setTemplateId(myObj.getTemplateId());
						@SuppressWarnings("unchecked")
						List<MockTestListBean> mockTestList = (List<MockTestListBean>) (Object) mockTestListServiceObj.doExecute(beanMT);
						if(mockTestList!=null && mockTestList.size()>0) {
							logger.info("Template ("+myObj.getTemplateId()+") Total MOCK TEST: "+mockTestList.size());
							cacheOrgObj.setMockTest(gson.toJson(mockTestList));
						}else {
							logger.info("No MOCK TEST Found for template: "+myObj.getTemplateId());
							
						}
						
						
						
				}
				
				if(cacheUpdate==0) {
					cacheOrgRepo.save(cacheOrgObj);
				}
				
			}	
					
			logger.info("**********************************************************************");
			logger.info("**** ORGANISATION CACHE FINISHED ");
			logger.info("**********************************************************************");
	        
			entityManager.getTransaction().commit();
			entityManager.close();
		        
		}catch(Exception e) {
			e.getStackTrace();
		}
		
		
		return loginResponseBeanObj;
		
	}
	

	
}
