package com.bizofficer.apiweb.testdetail;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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 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.hibernate.entity.MocktestManagement;
import com.bizofficer.hibernate.entity.MocktestQuestionAssociation;
import com.bizofficer.hibernate.entity.ModelTestManagement;
import com.bizofficer.hibernate.entity.PgprepCacheMocktest;
import com.bizofficer.hibernate.entity.QbAssessmentItem;
import com.bizofficer.hibernate.entity.QbGroupedItem;
import com.bizofficer.hibernate.repository.PgprepCacheMocktestRepository;
import com.bizofficer.hibernate.repository.PgprepTestSummaryRepository;
import com.bizofficer.module.questioncd.QuestionMapperBeanCD;
import com.bizofficer.module.questioncd.XmlToJsonCD;
import com.bizofficer.pojo.response.ListResponsePojo;
import com.bizofficer.util.module.BeanQuestion;
import com.bizofficer.util.module.MysqlTableNames;
import com.bizofficer.util.module.QuestionHtml;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;


@Service
public class MockTestAPIService{
	
	private static final Logger logger = Logger.getLogger(MockTestAPIService.class);
	
	@Autowired
	EntityManagerFactory entityManagerFactory;
	
	@Autowired
	PgprepTestSummaryRepository pgprepTestSummaryRepoObj; 
	
	@Autowired
	PgprepCacheMocktestRepository objCacheMocktestRepo;
	
	@Autowired
    DataSource appDataSource;
    Connection conn;
    PreparedStatement ps, psX;
    ResultSet rs, rsX;
	
	public Object doExecute(Object obj) throws NotFoundException{
		BeanTesting objBean = (BeanTesting) obj; 	
		ListResponsePojo responseObj = new ListResponsePojo();
		
		
		try {

			responseObj.setResponseTxt("failed");
			
			logger.info("Student_Id: " + objBean.getStudentId());
			logger.info("Organisation_Id: " + objBean.getOrganisationId());
			logger.info("TestId: " + objBean.getTestId());
			
			if(objBean.getTestId()==null) {
				return responseObj;
			}
		
			List<TestingPageBean> dataList = new ArrayList<TestingPageBean>();
			
			/// CHECK TEST PARAMETERS ******************************************
			if(objBean.getOrganisationId()!=null && objBean.getStudentId()!=null && objBean.getStudentId().length()>0) {
				conn = appDataSource.getConnection();
	            if(conn != null){
	            	String sqlPPP = "SELECT parameter_id FROM "+MysqlTableNames.getOrganisationParameterAssociation()+" WHERE organisation_id=? LIMIT 1 ";
	            	PreparedStatement psPPP = conn.prepareStatement(sqlPPP);
                    psPPP.setString(1, String.valueOf(objBean.getOrganisationId()));
                    logger.info(this.getClass().getName()+": " + psPPP);
                    ResultSet rsPP = psPPP.executeQuery();
                    if (rsPP.next()) {                    	
                    	String sqlQQQ = "SELECT max_model_test, max_single_model_mocktest FROM "+MysqlTableNames.getSelftestParameterManagement()+" WHERE max_test>0 AND id1=? LIMIT 1 ";
    	            	PreparedStatement psQQQ = conn.prepareStatement(sqlQQQ);
    	            	psQQQ.setInt(1, Integer.valueOf(rsPP.getString("parameter_id")));
                        logger.info(this.getClass().getName()+": " + psQQQ);
                        ResultSet rsQQQ = psQQQ.executeQuery();
                        if (rsQQQ.next()) {
                        	Integer totalTestGivenToday = pgprepTestSummaryRepoObj.countTestGivenToday(objBean.getStudentId(),3,objBean.getOrganisationId());
                        	logger.info("totalTestGivenToday: " + totalTestGivenToday);

                        	Integer totalTestGiven = pgprepTestSummaryRepoObj.countTestGiven(objBean.getStudentId(),3,objBean.getTestId());
                        	logger.info("Single Total Test Given: " + totalTestGiven);
                        	
                        	if(totalTestGivenToday>0 && rsQQQ.getInt("max_model_test")<=totalTestGivenToday) {
                        		TestingPageBean testingPageBeanObj = new TestingPageBean();
								testingPageBeanObj.setResponseTxt("Mock test limit has been exceeded for today.");
								
                        		String sqlOrg = "SELECT organisation_name FROM "+MysqlTableNames.getOrganisationInfo()+" WHERE organisation_id=? LIMIT 1 ";
            	            	PreparedStatement psOrg = conn.prepareStatement(sqlOrg);
            	            	psOrg.setString(1, String.valueOf(objBean.getOrganisationId()));
                                ResultSet rsOrg = psOrg.executeQuery();
                                if (rsOrg.next()) {
                                	if(rsOrg.getString("organisation_name").indexOf("FREE")>-1) {
                                		testingPageBeanObj.setResponseTxt("Mock test limit has been exceeded. You are registered as free account. Contact us to upgrade your account to increase test limit.");
                                	}
                                }	             
                                
								dataList.add(testingPageBeanObj);
																
								responseObj.setList(dataList);
								
								return responseObj;
								
                        	}else if(totalTestGiven>0 && rsQQQ.getInt("max_single_model_mocktest")<=totalTestGiven) {
	                        	TestingPageBean testingPageBeanObj = new TestingPageBean();
								testingPageBeanObj.setResponseTxt("Limit has been exceeded for this mock test.");
								dataList.add(testingPageBeanObj);
								
								responseObj.setList(dataList);
								
								return responseObj;
								
                        	}
                        	
                        }
                        psQQQ.close();
                        rsQQQ.close();
					}
                    psPPP.close();
                    rsPP.close();
	            }
	            conn.close();
			}
			

			PgprepCacheMocktest objCacheMocktest = objCacheMocktestRepo.findByMocktestGeneratedId(objBean.getTestId());
			if(objCacheMocktest!=null && objCacheMocktest.getId()>0 && objCacheMocktest.getTestDetail().length()>50) {
				ObjectMapper mapper = new ObjectMapper();
				dataList = mapper.readValue(objCacheMocktest.getTestDetail(), new TypeReference<List<TestingPageBean>>(){});
				logger.info("Mocktest Created From Cache");
				
				responseObj.setList(dataList);				
				responseObj.setResponseTxt("success");
				
				return responseObj;			
				
			}

			
			List<QuestionNumbersBean> questionNumbersList = new ArrayList<QuestionNumbersBean>();
			List<SectionSetBean> sectionSetList = new ArrayList<SectionSetBean>();
			SectionSetBean sectionSetBeanObj = new SectionSetBean();
			List<QuestionSetBean> questionSetList = new ArrayList<QuestionSetBean>();
			
			Integer totalAllSectionTime = 0;
			int currentSectionOrder = 0;
			
			EntityManager entityManager = entityManagerFactory.createEntityManager();
			entityManager.getTransaction().begin();
			
			TestingPageBean testingPageBeanObj = new TestingPageBean();
			
			int questionIndex = 0;
			
			TypedQuery<MocktestManagement> queryMTM = (TypedQuery<MocktestManagement>) entityManager.createQuery("from "+MocktestManagement.class.getName()+" where mocktestGeneratedId=:mocktestGeneratedId ", MocktestManagement.class);
			queryMTM.setParameter("mocktestGeneratedId", objBean.getTestId());
			queryMTM.setFirstResult(0);
			queryMTM.setMaxResults(1);
			List<?> resultListMTM = queryMTM.getResultList();
			Iterator<?> iteratorMTM = resultListMTM.iterator();
			if(iteratorMTM.hasNext()){
				MocktestManagement myObjMTM = (MocktestManagement)iteratorMTM.next();
                
				testingPageBeanObj.setTestId(myObjMTM.getMocktestGeneratedId());
				testingPageBeanObj.setTestType(3);
				testingPageBeanObj.setModelTestId(myObjMTM.getModelTestId());
				testingPageBeanObj.setTestName(myObjMTM.getMocktestGeneratedTitle());				
				testingPageBeanObj.setSectionLock("No_Lock");
				testingPageBeanObj.setLastQuestionIndex(0);
				
				logger.info( "Mocktest Id: " +   myObjMTM.getMocktestId() );
				logger.info( "Mocktest Generated Title: " +   myObjMTM.getMocktestGeneratedTitle() );
				logger.info( "Model Test Id: " +   myObjMTM.getModelTestId() );
				///this.getSectionArr(entityManager, 47);
				
				List<String> sectionList = new ArrayList<String>();
				Boolean sectionAllow = false;
				ModelTestManagement myObjMOTM = null;
				TypedQuery<ModelTestManagement> queryMOTM = (TypedQuery<ModelTestManagement>) entityManager.createQuery("from "+ModelTestManagement.class.getName()+" where modelTestId=:modelTestId ", ModelTestManagement.class);
				queryMOTM.setParameter("modelTestId", myObjMTM.getModelTestId());
				queryMOTM.setFirstResult(0);
				queryMOTM.setMaxResults(1);
				List<?> resultListMOTM = queryMOTM.getResultList();
				Iterator<?> iteratorMOTM = resultListMOTM.iterator();
				if(iteratorMOTM.hasNext()){
					myObjMOTM = (ModelTestManagement)iteratorMOTM.next();
					
					testingPageBeanObj.setTotalTime(myObjMOTM.getDuration());
					testingPageBeanObj.setRemainingTime(myObjMOTM.getDuration()*60);
					
					if(myObjMOTM.getSectionAllow()!=null && myObjMOTM.getSectionAllow()==1) {
						logger.info( "Section Allow: " +   myObjMOTM.getSectionAllow() );
						sectionAllow = true;
						sectionList = this.getSectionArr(myObjMOTM.getModelTestId());
					}
				}
				
				TypedQuery<MocktestQuestionAssociation> queryMQA = (TypedQuery<MocktestQuestionAssociation>) entityManager.createQuery("from "+MocktestQuestionAssociation.class.getName()+" where mocktestGeneratedId="+objBean.getTestId(), MocktestQuestionAssociation.class);
				List<?> resultListMQA = queryMQA.getResultList();
				
				logger.info("MocktestQuestionAssociation resultListMQA Size: "+resultListMQA.size());
				
				Iterator<?> iteratorMQA = resultListMQA.iterator();				
				while(iteratorMQA.hasNext()){
					MocktestQuestionAssociation myObjMQA = (MocktestQuestionAssociation)iteratorMQA.next();

					logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
					logger.info("MocktestQuestionAssociation Assess Id: "+myObjMQA.getAssessId());
					logger.info("MocktestQuestionAssociation MockQuesAssoNo: "+myObjMQA.getMockQuesAssoNo());
					
					TypedQuery<QbAssessmentItem> queryASTM = (TypedQuery<QbAssessmentItem>) entityManager.createQuery("from "+QbAssessmentItem.class.getName()+" where assessId="+myObjMQA.getAssessId(), QbAssessmentItem.class);
					queryASTM.setFirstResult(0);
					queryASTM.setMaxResults(1);
					List<?> resultListASTM = queryASTM.getResultList();
					Iterator<?> iteratorASTM = resultListASTM.iterator();
					if(iteratorASTM.hasNext()){
						QbAssessmentItem myObjASTM = (QbAssessmentItem)iteratorASTM.next();
						
						logger.info("QbAssessmentItem Assess Id: "+myObjASTM.getAssessId());
						
						String topicId = null;
						/// FETCH TOPIC
//						TypedQuery<QbItems> queryQBI = (TypedQuery<QbItems>) entityManager.createQuery("from "+QbItems.class.getName()+" where itemId="+myObjMQA.getAssessId(), QbItems.class);
//						queryQBI.setFirstResult(0);
//						queryQBI.setMaxResults(1);
//						List<?> resultListQBI = queryQBI.getResultList();
//						Iterator<?> iteratorQBI = resultListQBI.iterator();
//						if(iteratorQBI.hasNext()){
//							QbItems myObjQBI = (QbItems)iteratorQBI.next();
//							topicId = myObjQBI.getQbId();
//						}

						conn = appDataSource.getConnection();
				        if(conn != null){
				        	String sqlA = "SELECT * FROM qb_items WHERE item_id=? LIMIT 1";
				        	PreparedStatement stmtA = conn.prepareStatement(sqlA);
				        	stmtA.setInt(1, myObjMQA.getAssessId());
				            logger.info(this.getClass().getName()+": " + stmtA);
				            ResultSet myObjQBI = stmtA.executeQuery();
				            if(myObjQBI.next()) {  
				            	topicId = myObjQBI.getString("qb_id");
				            }		
				            myObjQBI.close();
				            stmtA.close();
				        }  
				        conn.close();
				        
						//*******************************************************************************
						//	COMMON DATA QUESTION TYPE
						//*******************************************************************************
						if( "Common Data".equals(myObjASTM.getAssessTitle()) || "Common Data (5)".equals(myObjASTM.getAssessTitle())  ) {

							QuestionMapperBeanCD questionObj = (QuestionMapperBeanCD) new XmlToJsonCD().parse(myObjASTM.getAssessText());
							
								TypedQuery<QbGroupedItem> queryGBGI = (TypedQuery<QbGroupedItem>) entityManager.createQuery("from "+QbGroupedItem.class.getName()+" where assessId="+myObjASTM.getAssessId(), QbGroupedItem.class);
								queryGBGI.setFirstResult(0);
								queryGBGI.setMaxResults(myObjMQA.getNoOfQuestion());
								List<?> resultListGBGI = queryGBGI.getResultList();
								Iterator<?> iteratorGBGI = resultListGBGI.iterator();
								while(iteratorGBGI.hasNext()){
									QbGroupedItem myObjGBGI = (QbGroupedItem)iteratorGBGI.next();
									///logger.info("Item ID >> " + myObjGBGI.getItemId()  );
									
									//*******************************************************************************
									//	QUESTION SET START
									//*******************************************************************************
									QuestionSetBean questionSetBeanObj = new QuestionSetBean();
									
									logger.info("QbGroupedItem Assess Id: "+myObjGBGI.getItemId()*10000);
									logger.info("QbGroupedItem Assess Title: "+myObjGBGI.getItemTitle());
									logger.info(" PASSING TO PARSER ");
									logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");						
									
									BeanQuestion bqObj = new BeanQuestion();
									bqObj.setQuestionId(myObjGBGI.getItemId()*10000);
									bqObj.setItemId(myObjGBGI.getItemId());
									bqObj.setQuestionDisplayId(String.valueOf(myObjGBGI.getDisplayId()));
									bqObj.setQuestionType(myObjGBGI.getItemTitle());
									bqObj.setQuestionTypeLabel(myObjGBGI.getItemTitle());
									bqObj.setQuestionBody(myObjGBGI.getItemText());
									bqObj.setCommonDataDescription(questionObj.getItem().getDescription());
									////bqObj.setCommonDataDescription("Consider an ionic solid that dissolves in water according");

									questionSetBeanObj = new QuestionHtml().getXmlParser(bqObj,false);
									
									questionSetBeanObj.setTopicId(topicId);
									questionSetBeanObj.setTimeSpent(0);
									questionSetBeanObj.setCssName("qbg-not-visited");
									questionSetBeanObj.setBackgroundImg("url('/not-visited.png')");
									
									//*******************************************************************************
									//	SECTION START
									//*******************************************************************************
									if(Boolean.TRUE.equals(sectionAllow) && sectionList!=null && sectionList.size()>0) {			
										String[] sectionArr = sectionList.get(questionIndex).split("#");
										if(sectionArr[0]!=null) {
											
											questionSetBeanObj.setSectionName(sectionArr[0]);
											questionSetBeanObj.setSectionOrder(Integer.valueOf(sectionArr[1]));
											questionSetBeanObj.setSectionTime(Integer.valueOf(sectionArr[2])*60);
											questionSetBeanObj.setCorrectAnswerMarks(Double.valueOf(sectionArr[3]));
											questionSetBeanObj.setIncorrectAnswerMarks(Double.valueOf(sectionArr[4]));
											questionSetBeanObj.setNotAnswerMarks(Double.valueOf(sectionArr[5]));
											questionSetBeanObj.setSectionId(Integer.valueOf(sectionArr[6]));
											
											if(sectionArr[2]!=null && Integer.valueOf(sectionArr[2])>0) {
												totalAllSectionTime += Integer.valueOf(sectionArr[2]);
											}
											
											
											logger.info("currentSectionOrder CD: "+currentSectionOrder);
											logger.info("sectionArr[1] CD: "+sectionArr[1]);
											
											if(currentSectionOrder<Integer.valueOf(sectionArr[1])) {
												sectionSetBeanObj = new SectionSetBean();
												sectionSetBeanObj.setSectionName(sectionArr[0]);
												
												if(sectionArr[2]!=null && Integer.valueOf(sectionArr[2])>0) {
													sectionSetBeanObj.setSectionTime(Integer.valueOf(sectionArr[2])*60);
												}
												
												questionNumbersList = new ArrayList<QuestionNumbersBean>();
												
												QuestionNumbersBean questionNumbersBeanObj = new QuestionNumbersBean();
												questionNumbersBeanObj.setQuestionIndex(questionIndex);
												questionNumbersBeanObj.setQuestionId(myObjGBGI.getItemId()*10000);
												questionNumbersList.add(questionNumbersBeanObj);
												
												sectionSetBeanObj.setQuestionNumbers(questionNumbersList);
																					
											}else {
												QuestionNumbersBean questionNumbersBeanObj = new QuestionNumbersBean();
												questionNumbersBeanObj.setQuestionIndex(questionIndex);
												questionNumbersBeanObj.setQuestionId(myObjGBGI.getItemId()*10000);
												questionNumbersList.add(questionNumbersBeanObj);
											}
											
											if(currentSectionOrder<Integer.valueOf(sectionArr[1])) {
												sectionSetList.add(sectionSetBeanObj);
												currentSectionOrder = Integer.valueOf(sectionArr[1]);
											}	
											
											
										}
									}else { /// if section allow is false
										
										questionSetBeanObj.setCorrectAnswerMarks(myObjMOTM.getMarksCorrectAns());
										questionSetBeanObj.setIncorrectAnswerMarks(myObjMOTM.getMarksIncorrectAns());
										questionSetBeanObj.setNotAnswerMarks(myObjMOTM.getMarksNotAns());
										
										QuestionNumbersBean questionNumbersBeanObj = new QuestionNumbersBean();
										questionNumbersBeanObj.setQuestionIndex(questionIndex);
										questionNumbersBeanObj.setQuestionId(myObjGBGI.getItemId()*10000);
										questionNumbersList.add(questionNumbersBeanObj);
										
									}									
									
									
									//*******************************************************************************
									//	SECTION END
									//*******************************************************************************
									
									questionSetList.add(questionSetBeanObj);
									
									logger.info("questionIndex: "+questionIndex);
									
									questionIndex++;
									
									//*******************************************************************************
									//	QUESTION SET END
									//*******************************************************************************
									
								}
								
						//*******************************************************************************
						//	OTHER QUESTION TYPES THAN COMMON DATA
						//*******************************************************************************
						}else {							
							
							
							//*******************************************************************************
							//	QUESTION SET START
							//*******************************************************************************
							QuestionSetBean questionSetBeanObj = new QuestionSetBean();
							
							logger.info("QbGroupedItem Assess Id: "+myObjASTM.getAssessId());
							logger.info("QbGroupedItem Assess Title: "+myObjASTM.getAssessTitle());
							logger.info(" PASSING TO PARSER ");
							logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");						
							
							BeanQuestion bqObj = new BeanQuestion();
							bqObj.setQuestionId(myObjASTM.getAssessId());
							bqObj.setItemId(null);
							bqObj.setQuestionDisplayId(String.valueOf(myObjASTM.getDisplayId()));
							bqObj.setQuestionType(myObjASTM.getAssessTitle());
							bqObj.setQuestionTypeLabel(myObjASTM.getAssessTitle());
							bqObj.setQuestionBody(myObjASTM.getAssessText());
							bqObj.setCommonDataDescription(null);

							questionSetBeanObj = new QuestionHtml().getXmlParser(bqObj,false);
							
							questionSetBeanObj.setTopicId(topicId);
							questionSetBeanObj.setTimeSpent(0);
							questionSetBeanObj.setCssName("qbg-not-visited");
							questionSetBeanObj.setBackgroundImg("url('/not-visited.png')");
							
							//*******************************************************************************
							//	SECTION START
							//*******************************************************************************
							if(Boolean.TRUE.equals(sectionAllow) && sectionList!=null && sectionList.size()>0) {			
								String[] sectionArr = sectionList.get(questionIndex).split("#");
								if(sectionArr[0]!=null) {
									
									logger.info("SectionName: "+sectionArr[0]);
									
									questionSetBeanObj.setSectionName(sectionArr[0]);
									questionSetBeanObj.setSectionOrder(Integer.valueOf(sectionArr[1]));
									
									logger.info("SectionTime AA: "+sectionArr[2]);
									
									if(sectionArr[2]!=null && Integer.valueOf(sectionArr[2])>0) {
										totalAllSectionTime += Integer.valueOf(sectionArr[2]);
									}
									
									logger.info("totalAllSectionTime AA: "+totalAllSectionTime);
									
									questionSetBeanObj.setSectionTime(Integer.valueOf(sectionArr[2])*60);
									
									logger.info("SectionTime BB: "+questionSetBeanObj.getSectionTime());
									
									questionSetBeanObj.setCorrectAnswerMarks(Double.valueOf(sectionArr[3]));
									questionSetBeanObj.setIncorrectAnswerMarks(Double.valueOf(sectionArr[4]));
									questionSetBeanObj.setNotAnswerMarks(Double.valueOf(sectionArr[5]));
									questionSetBeanObj.setSectionId(Integer.valueOf(sectionArr[6]));
									
																		
									
									logger.info("currentSectionOrder: "+currentSectionOrder);
									logger.info("sectionArr[1]: "+sectionArr[1]);
									
									if(currentSectionOrder<Integer.valueOf(sectionArr[1])) {
										sectionSetBeanObj = new SectionSetBean();
										sectionSetBeanObj.setSectionName(sectionArr[0]);
										
										if(sectionArr[2]!=null && Integer.valueOf(sectionArr[2])>0) {
											sectionSetBeanObj.setSectionTime(Integer.valueOf(sectionArr[2])*60);
										}
										
										questionNumbersList = new ArrayList<QuestionNumbersBean>();
										
										QuestionNumbersBean questionNumbersBeanObj = new QuestionNumbersBean();
										questionNumbersBeanObj.setQuestionIndex(questionIndex);
										questionNumbersBeanObj.setQuestionId(myObjASTM.getAssessId());
										questionNumbersList.add(questionNumbersBeanObj);
										
										sectionSetBeanObj.setQuestionNumbers(questionNumbersList);
																			
									}else {
										QuestionNumbersBean questionNumbersBeanObj = new QuestionNumbersBean();
										questionNumbersBeanObj.setQuestionIndex(questionIndex);
										questionNumbersBeanObj.setQuestionId(myObjASTM.getAssessId());
										questionNumbersList.add(questionNumbersBeanObj);
									}
									
									if(currentSectionOrder<Integer.valueOf(sectionArr[1])) {
										sectionSetList.add(sectionSetBeanObj);
										currentSectionOrder = Integer.valueOf(sectionArr[1]);
									}	
									
									
								}
							}else { /// if section allow is false
								
								questionSetBeanObj.setCorrectAnswerMarks(myObjMOTM.getMarksCorrectAns());
								questionSetBeanObj.setIncorrectAnswerMarks(myObjMOTM.getMarksIncorrectAns());
								questionSetBeanObj.setNotAnswerMarks(myObjMOTM.getMarksNotAns());
								
								QuestionNumbersBean questionNumbersBeanObj = new QuestionNumbersBean();
								questionNumbersBeanObj.setQuestionIndex(questionIndex);
								questionNumbersBeanObj.setQuestionId(myObjASTM.getAssessId());
								questionNumbersList.add(questionNumbersBeanObj);
								
							}
							
														
							//*******************************************************************************
							//	SECTION END
							//*******************************************************************************
							
							questionSetList.add(questionSetBeanObj);
							
							logger.info("questionIndex: "+questionIndex);
							
							questionIndex++;
							
							
							//*******************************************************************************
							//	QUESTION SET END
							//*******************************************************************************
						
							
						} /// ELSE CLOSE OF OTHER QUESITION TYPES
						
						
						
						
						
						
					}					
				}	
				
				
				if(Boolean.FALSE.equals(sectionAllow)) {
					sectionSetBeanObj.setQuestionNumbers(questionNumbersList);
					sectionSetList.add(sectionSetBeanObj);
				}
				
			} 
			
			if(totalAllSectionTime>0) {
				
//				logger.info("ZZ totalAllSectionTime: "+totalAllSectionTime);
				
//				testingPageBeanObj.setTotalTime(totalAllSectionTime);
//				testingPageBeanObj.setRemainingTime(totalAllSectionTime*60);
				testingPageBeanObj.setSectionLock("Partially_Lock");
			}
			
			testingPageBeanObj.setSectionSet(sectionSetList);
			testingPageBeanObj.setQuestionSet(questionSetList);
			dataList.add(testingPageBeanObj);
			
			entityManager.getTransaction().commit();
			entityManager.close();
			
			if(dataList!=null && questionSetList.size()>2) {
				Gson gson = new Gson();
				PgprepCacheMocktest objPgprepCacheMocktest = new PgprepCacheMocktest();
				objPgprepCacheMocktest.setMocktestGeneratedId(objBean.getTestId());
				objPgprepCacheMocktest.setTestDetail(gson.toJson(dataList));
				objCacheMocktestRepo.save(objPgprepCacheMocktest);
				logger.info("CACHE CREATED");
			}
			
			logger.info("**************************************************************************");
			
			if(sectionSetList!=null) {
				logger.info("sectionSetList Count: "+sectionSetList.size());
			}
			
			if(questionSetList!=null) {
				logger.info("questionSetList Count: "+questionSetList.size());
			}
			
			logger.info("TEST API CREATED");
			
			logger.info("**************************************************************************");
			
			responseObj.setList(dataList);
			
			responseObj.setResponseTxt("success");
			
		}catch(Exception e) {
			e.getStackTrace();
		}
		
		////logger.info( "dataList >>> " +  dataList );
			
		return responseObj;
	}

	
	
	private List<String> getSectionArr(Integer modelTestId) {
		List<String> sectionList = new ArrayList<String>();
		
		try {
		
				logger.info("SectionArr modelTestId >>> " + modelTestId  );
				
				conn = appDataSource.getConnection();
		        if(conn != null){
		        	String sqlA = "SELECT * FROM "+MysqlTableNames.getModelSectionManagement()+" WHERE model_id=? ";
		        	PreparedStatement stmtA = conn.prepareStatement(sqlA);
		        	stmtA.setInt(1, modelTestId);
		            logger.info(this.getClass().getName()+": " + stmtA);
		            ResultSet myObjMSM = stmtA.executeQuery();
		            int sectionOrder=0;
		            while (myObjMSM.next()) {  
			        	String sqlB = "SELECT * FROM "+MysqlTableNames.getSectionManagement()+"  WHERE section_id=? order by section_id asc ";
			        	PreparedStatement stmtB = conn.prepareStatement(sqlB);
			        	stmtB.setInt(1, myObjMSM.getInt("section_id"));
			            logger.info(this.getClass().getName()+": " + stmtB);
			            ResultSet myObjSMM = stmtB.executeQuery();
			            while (myObjSMM.next()) {  
							sectionOrder+=1;
							for(int i=1; i<=myObjSMM.getInt("no_question"); i++) {
								sectionList.add(myObjSMM.getString("section_name")+"#"+sectionOrder+"#"+myObjSMM.getInt("section_time")+"#"+myObjSMM.getDouble("correct_marks")+"#"+myObjSMM.getDouble("incorrect_marks")+"#"+myObjSMM.getDouble("no_answer_marks")+"#"+myObjSMM.getInt("section_id"));
							}
							
						}
			            myObjSMM.close();
			            stmtB.close();
						
		            }	
		            myObjMSM.close();
		            stmtA.close();
				}
		        conn.close();
				
				logger.info( "sectionList Size >>> " +   sectionList.size() );
				int i = 0;
				for(String str : sectionList){
					logger.info( "str >>> " +i+ " == " +   str );
					i++;
			    }
				
				///logger.info( "sectionList >>> " +   sectionList.toString() );
				
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		return sectionList;
		
	}


//	private List<String> getSectionArr(EntityManager entityManager, Integer modelTestId) {
//		List<String> sectionList = new ArrayList<String>();
//		
//		logger.info("SectionArr modelTestId >>> " + modelTestId  );
//		
//		TypedQuery<ModelSectionManagement> queryMSM = (TypedQuery<ModelSectionManagement>) entityManager.createQuery("from "+ModelSectionManagement.class.getName()+" where modelId="+modelTestId, ModelSectionManagement.class);
//		List<?> resultListMSM = queryMSM.getResultList();
//		Iterator<?> iteratorMSM = resultListMSM.iterator();
//		int sectionOrder=0;
//		while(iteratorMSM.hasNext()){
//			ModelSectionManagement myObjMSM = (ModelSectionManagement)iteratorMSM.next();
//			////logger.info(  "myObjMSM.getSectionId() >>> " + myObjMSM.getSectionId()  );
//				TypedQuery<SectionManagement> querySM = (TypedQuery<SectionManagement>) entityManager.createQuery("from "+SectionManagement.class.getName()+" where sectionId="+myObjMSM.getSectionId()+" order by sectionId asc ", SectionManagement.class);
//				List<?> resultListSMM = querySM.getResultList();
//				Iterator<?> iteratorSMM=resultListSMM.iterator();				
//				while(iteratorSMM.hasNext()){
//					SectionManagement myObjSMM = (SectionManagement)iteratorSMM.next();
//									
//					sectionOrder+=1;
//					for(int i=1; i<=myObjSMM.getNoQuestion(); i++) {
//						sectionList.add(myObjSMM.getSectionName()+"#"+sectionOrder+"#"+myObjSMM.getSectionTime()+"#"+myObjSMM.getCorrectMarks()+"#"+myObjSMM.getIncorrectMarks()+"#"+myObjSMM.getNoAnswerMarks()+"#"+myObjSMM.getSectionId());
//					}
//					
//				}	
//		}
//		
//		logger.info( "sectionList Size >>> " +   sectionList.size() );
//		int i = 0;
//		for(String str : sectionList){
//			logger.info( "str >>> " +i+ " == " +   str );
//			i++;
//	    }
//		
//		///logger.info( "sectionList >>> " +   sectionList.toString() );
//		
//		return sectionList;
//	}
	
	
	
	
	
}
