package com.bizofficer.apiweb.dashboard;

import java.math.BigDecimal;
import java.math.MathContext;
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.PgprepTestSummary;
import com.bizofficer.pojo.response.ListResponsePojo;


@Service
public class DashboardService{
	
	private static final Logger logger = Logger.getLogger(DashboardService.class);

	
	@Autowired
	EntityManagerFactory entityManagerFactory;
	
	public Object doExecute(Object obj) throws NotFoundException{
		BeanDashboard objBean = (BeanDashboard) obj; 
		ListResponsePojo responseObj = new ListResponsePojo();
		
		try {
			
			responseObj.setResponseTxt("failed");
			
			if(objBean.getStudentId()==null || objBean.getOrganisationId()==null) {
				return responseObj;
			}

			List<DashboardPageBean> dataList = new ArrayList<DashboardPageBean>();

			DashboardPageBean dashboardPageBeanObj = null;
			ReportBean reportBeanObj = null;
			BigDecimal bigDecimalVal;
			Double answerDivision = 0.0;
			Integer totalAttempted = 0;
			String answerDivisionStr = null;
		
			EntityManager entityManager = entityManagerFactory.createEntityManager();
			entityManager.getTransaction().begin();
			
			String[] testTypeArr = {"Self Assessor","Topic Test","Mock Test","Class Test"};
			
			for(int i=1; i<=4; i++) {
				
				TypedQuery<PgprepTestSummary> query = (TypedQuery<PgprepTestSummary>) entityManager.createQuery("from "+PgprepTestSummary.class.getName()+" where organisationId="+objBean.getOrganisationId()+" and studentId='"+objBean.getStudentId()+"' and testType="+i+" and testStatus=1 order by id desc ", PgprepTestSummary.class);
				query.setFirstResult(0);
				query.setMaxResults(1);			
				List<?> resultList = query.getResultList();
				Iterator<?> iterator=resultList.iterator();
				if(iterator.hasNext()){
					PgprepTestSummary myObj = (PgprepTestSummary)iterator.next();
					
					dashboardPageBeanObj = new DashboardPageBean();
				
					logger.info("TestTypeArr >>> " + testTypeArr[i-1]);
					
					dashboardPageBeanObj.setTestType(testTypeArr[i-1]);
					
					/****************************************************************
					 * 		Last Report
					 * **************************************************************/
					List<ReportBean> testLastReportList = new ArrayList<ReportBean>();
						
					logger.info("TestTitle >>> " + myObj.getTestTitle() );
					
						dashboardPageBeanObj.setTestLastTopic(myObj.getTestTitle());
						
						if(myObj.getAnswerDivision()!=null && myObj.getAnswerDivision().length()>0 ) {
							
							logger.info("AnswerDivision >>> " + myObj.getAnswerDivision() );
							
							String[] answerDivisionArr = myObj.getAnswerDivision().split("\\|");
							
							answerDivision = (Double.valueOf(answerDivisionArr[0])*100)/myObj.getTotalQuestion();
							answerDivisionStr = String.format("%1.2f", answerDivision);							
							reportBeanObj = new ReportBean();
							reportBeanObj.setY(Double.valueOf(answerDivisionStr));
							reportBeanObj.setName("Correct: "+answerDivisionArr[0]+"/"+myObj.getTotalQuestion());
							reportBeanObj.setColor("#46d39a");
							testLastReportList.add(reportBeanObj);
							
							answerDivision = (Double.valueOf(answerDivisionArr[1])*100)/myObj.getTotalQuestion();
							answerDivisionStr = String.format("%1.2f", answerDivision);								
							reportBeanObj = new ReportBean();
							reportBeanObj.setY(Double.valueOf(answerDivisionStr));
							reportBeanObj.setName("Incorrect: "+answerDivisionArr[1]+"/"+myObj.getTotalQuestion());
							reportBeanObj.setColor("#e55759");
							testLastReportList.add(reportBeanObj);
				
							answerDivision = (Double.valueOf(answerDivisionArr[2])*100)/myObj.getTotalQuestion();
							answerDivisionStr = String.format("%1.2f", answerDivision);								
							reportBeanObj = new ReportBean();
							reportBeanObj.setY(Double.valueOf(answerDivisionStr));
							reportBeanObj.setName("Not Answer: "+answerDivisionArr[2]+"/"+myObj.getTotalQuestion());
							reportBeanObj.setColor("#4198d7");
							testLastReportList.add(reportBeanObj);
							
						}	
						
					dashboardPageBeanObj.setTestLastReport(testLastReportList);
		
					/****************************************************************
					 * 		Last 5 Exam
					 * **************************************************************/
					String lastPerformance = null;
					List<String> testLastTestsXList = new ArrayList<String>();
					List<TestsYBean> testLastTestsYList = new ArrayList<TestsYBean>();
					TestsYBean testsYBeanObj;
					TypedQuery<PgprepTestSummary> query2 = (TypedQuery<PgprepTestSummary>) entityManager.createQuery("from "+PgprepTestSummary.class.getName()+" where organisationId="+objBean.getOrganisationId()+" and studentId='"+objBean.getStudentId()+"' and testType="+i+" and testStatus=1 order by id desc ", PgprepTestSummary.class);
					query2.setFirstResult(0);
					query2.setMaxResults(5);			
					List<?> resultList2 = query2.getResultList();
					Iterator<?> iterator2=resultList2.iterator();
					while(iterator2.hasNext()){
						PgprepTestSummary myObjA = (PgprepTestSummary)iterator2.next();
						
						   logger.info( "Marks Obtain >>> " + myObjA.getMarksObtain() );
						   logger.info( "Full Marks >>> " + myObjA.getFullMarks() );
						   logger.info( "Test Title >>> " + myObjA.getTestTitle() );
						
							bigDecimalVal = (myObjA.getMarksObtain().multiply(new BigDecimal(100))).divide(myObjA.getFullMarks(), new MathContext(2));
						
							testLastTestsXList.add(myObjA.getTestTitle());
		
							testsYBeanObj = new TestsYBean();							
							testsYBeanObj.setY(bigDecimalVal);
							if(bigDecimalVal!=null && bigDecimalVal.compareTo(new BigDecimal(0))==-1) {
								testsYBeanObj.setColor("#e82335");
							}else {
								testsYBeanObj.setColor("#32cd32");
							}
							
							if(myObjA.getTestType()!=null && myObjA.getTestType()==3) {
								testsYBeanObj.setTestDetails("analytics?testId="+myObjA.getTestSession()); 
							}else {
								testsYBeanObj.setTestDetails("testanalytics?testId="+myObjA.getTestSession());
							}
							
							testLastTestsYList.add(testsYBeanObj);
						
						
					}
					if(testLastTestsYList!=null && testLastTestsYList.size()==1) {
						lastPerformance = "Last Performance";
					}else if(testLastTestsYList!=null && testLastTestsYList.size()>1) {
						lastPerformance = "Last "+testLastTestsYList.size()+" Performances";
					}
					dashboardPageBeanObj.setLastPerformance(lastPerformance);
					dashboardPageBeanObj.setTestLastTestsY(testLastTestsYList);
					dashboardPageBeanObj.setTestLastTestsX(testLastTestsXList);
					
		
					/****************************************************************
					 * 		accuracy of attempted
					 * **************************************************************/
					
					List<ReportBean> testAccuracyList = new ArrayList<ReportBean>();
					
					TypedQuery<PgprepTestSummary> query3 = (TypedQuery<PgprepTestSummary>) entityManager.createQuery("from "+PgprepTestSummary.class.getName()+" where organisationId="+objBean.getOrganisationId()+" and studentId='"+objBean.getStudentId()+"' and testType="+i+" and testStatus=1 order by id desc ", PgprepTestSummary.class);
					query3.setFirstResult(0);
					query3.setMaxResults(1);			
					List<?> resultList3 = query3.getResultList();
					Iterator<?> iterator3=resultList3.iterator();
					if(iterator3.hasNext()){
						PgprepTestSummary myObjY = (PgprepTestSummary)iterator3.next();
						
						
						if(myObjY.getAnswerDivision()!=null && myObjY.getAnswerDivision().length()>0 ) {
							
							logger.info( "myObjY_Answer Division >>> " + myObjY.getAnswerDivision() );
							
							String[] answerDivisionArr = myObjY.getAnswerDivision().split("\\|");
							
							totalAttempted = Integer.valueOf(answerDivisionArr[0])+Integer.valueOf(answerDivisionArr[1]);
							
							if(totalAttempted>0) {
								answerDivision = (Double.valueOf(answerDivisionArr[0])*100)/totalAttempted;
								answerDivisionStr = String.format("%1.2f", answerDivision);								
								reportBeanObj = new ReportBean();
								reportBeanObj.setY(Double.valueOf(answerDivisionStr));
								reportBeanObj.setName("Correct: "+answerDivisionArr[0]+"/"+totalAttempted);
								reportBeanObj.setColor("#00FF00");
								testAccuracyList.add(reportBeanObj);
	
								answerDivision = (Double.valueOf(answerDivisionArr[1])*100)/totalAttempted;
								answerDivisionStr = String.format("%1.2f", answerDivision);
								reportBeanObj = new ReportBean();
								reportBeanObj.setY(Double.valueOf(answerDivisionStr));
								reportBeanObj.setName("Incorrect: "+answerDivisionArr[1]+"/"+totalAttempted);
								reportBeanObj.setColor("#FF0000");
								testAccuracyList.add(reportBeanObj);							
							}
							
						}	
						
					}
					
					dashboardPageBeanObj.setTestAccuracy(testAccuracyList);
					
					dataList.add(dashboardPageBeanObj);
					
				}			
				
				
			}
			
			
			entityManager.getTransaction().commit();
			entityManager.close();
			
			logger.info( "dataList >>> " +  dataList );
			
			responseObj.setList(dataList);
			
			responseObj.setResponseTxt("success");
			
		}catch(Exception e) {
			e.getStackTrace();
		}
		
					
		return responseObj;
	}
	

	
}
