package com.bizofficer.admin.students;



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.PgprepStudentCourses;
import com.bizofficer.hibernate.entity.SubscriptionCourses;
import com.bizofficer.hibernate.repository.PgprepAdministratorRepository;
import com.bizofficer.hibernate.repository.PgprepTestSummaryRepository;
import com.bizofficer.util.module.PrivilegesBeans;
import com.bizofficer.util.module.PrivilegesUtil;
import com.bizofficer.util.module.RoleModules;
import com.bizofficer.util.system.MakeDate;


@Service
public class StudentValidityAdminService{
	
	private static final Logger logger = Logger.getLogger(StudentValidityAdminService.class);
	
	@Autowired
	EntityManagerFactory entityManagerFactory;
	
	@Autowired
	PgprepAdministratorRepository adminRepo;
	
	@Autowired
    PgprepTestSummaryRepository testSumRepo;
	
	public Object execute(Object obj) throws NotFoundException{
		StudentAdminBean objBean = (StudentAdminBean) obj;
		StudentAdmResponsePojo responseObj = new StudentAdmResponsePojo();
		
		try {
			
			logger.info("getLoginEmailId >> " + objBean.getLoginEmailId() );
			logger.info("Token >> " + objBean.getToken() );
			logger.info("Auto Id >> " + objBean.getId() );
			logger.info("Course Id >> " + objBean.getCourseId() );
			logger.info("Student Id >> " + objBean.getStudentId() );
			logger.info("Organisation Id >> " + objBean.getOrganisationId() );
			logger.info("Validity Date >> " + objBean.getValidityDate() );
			logger.info("Subscription Type >> " + objBean.getSubscriptionType() );
			
			
			if(objBean.getLoginEmailId()==null || objBean.getToken()==null) {
				return responseObj;
			}
			
			PgprepAdministrator adminObj = (PgprepAdministrator) adminRepo.findByEmailIdAndLoginToken(objBean.getLoginEmailId(), objBean.getToken());
			if(adminObj==null) {
				logger.info("InvalidToken");
				responseObj.setResponseTxt("InvalidToken");
				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.getStudents() );
				logger.info(prvgbnObj.toString());
				if(prvgbnObj==null || (prvgbnObj!=null && (prvgbnObj.getUpdate()==null || prvgbnObj.getUpdate()==0))) {
					logger.info("NoAuthorization");
					responseObj.setResponseTxt("NoAuthorization");
					return responseObj;
				}
			}
			
			EntityManager entityManager = entityManagerFactory.createEntityManager();
			entityManager.getTransaction().begin();
			MakeDate mkdateObj = new MakeDate();
			Integer oldOrganisationId = objBean.getOrganisationId();

			// FIND PAID ORGANISATION
			if(objBean.getCourseId()!=null && objBean.getCourseId()>0 && "PAID".equals(objBean.getSubscriptionType())) {
				TypedQuery<SubscriptionCourses> query = (TypedQuery<SubscriptionCourses>) entityManager.createQuery("from "+SubscriptionCourses.class.getName()+" WHERE courseId=:courseId ", SubscriptionCourses.class);
				query.setParameter("courseId", objBean.getCourseId());
				query.setFirstResult(0);
				query.setMaxResults(1);
				List<?> resultListCat = query.getResultList();
				Iterator<?> iteratorCat=resultListCat.iterator();	
				if(iteratorCat.hasNext()){
					SubscriptionCourses myObj = (SubscriptionCourses)iteratorCat.next();	
					logger.info("PaidOrganisationId >> " + myObj.getPaidOrganisationId() );
					logger.info("FreeOrganisationId >> " + myObj.getFreeOrganisationId() );
					if("PAID".equals(objBean.getSubscriptionType())) {						
						objBean.setOrganisationId(myObj.getPaidOrganisationId());
					}
				}	
			}
			
			logger.info("Organisation Id >> " + objBean.getOrganisationId() );
			
			if(objBean.getUpdateDate()==1) {
				PgprepStudentCourses findObj = (PgprepStudentCourses)entityManager.find(PgprepStudentCourses.class ,objBean.getId());
				if(objBean.getValidityDate()!=null && objBean.getValidityDate().length()>2 ) {
					findObj.setValidTillDate(mkdateObj.getStringToDate(objBean.getValidityDate(), "yyyy-MM-dd"));
				}
			}else if(objBean.getUpdateDate()==0) {
				PgprepStudentCourses findObj = (PgprepStudentCourses)entityManager.find(PgprepStudentCourses.class ,objBean.getId());
				if(objBean.getValidityDate()!=null && objBean.getValidityDate().length()>2 ) {
					findObj.setValidTillDate(mkdateObj.getStringToDate(objBean.getValidityDate(), "yyyy-MM-dd"));
				}
				findObj.setOrganisationId(objBean.getOrganisationId());
				findObj.setSubscriptionType(objBean.getSubscriptionType());
				
				//*****************************************************
				logger.info("ORGANIZATION ONE = "+oldOrganisationId);
				logger.info("ORGANIZATION TWO = "+objBean.getOrganisationId());
				if("PAID".equals(objBean.getSubscriptionType()) && oldOrganisationId!=objBean.getOrganisationId() ) {
					logger.info("REPLACE ORGANIZATION ID IN TEST SUMMARY");
					
					testSumRepo.replaceOrgId(oldOrganisationId, objBean.getStudentId(), objBean.getOrganisationId());
					
				}
				
			}
			
			
			responseObj.setResponseTxt("OK");
			
			entityManager.getTransaction().commit();
			entityManager.close();
		        
		}catch(Exception e) {
			e.getStackTrace();
		}
		
		
		return responseObj;
	}
	

	
	

	
	
}
