package com.bizofficer.admin.navigation;



import java.util.List;

import javax.persistence.EntityManagerFactory;

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.OrganisationInfo;
import com.bizofficer.hibernate.entity.PgprepAdministrator;
import com.bizofficer.hibernate.repository.OrganisationInfoRepository;
import com.bizofficer.hibernate.repository.PgprepAdministratorRepository;
import com.bizofficer.util.module.PrivilegesBeans;
import com.bizofficer.util.module.PrivilegesUtil;
import com.bizofficer.util.module.RoleModules;


@Service
public class NavigationOrgAdminService{
	
	private static final Logger logger = Logger.getLogger(NavigationOrgAdminService.class);
	
	@Autowired
	EntityManagerFactory entityManagerFactory;
	
	@Autowired
	PgprepAdministratorRepository adminRepo;
	
	@Autowired
	OrganisationInfoRepository stRepo;
	
	public Object execute(Object obj) throws NotFoundException{
		NavigationAdminBean objBean = (NavigationAdminBean) obj;
		NavigationAdmResponseBean responseObj = new NavigationAdmResponseBean();
		
		try {
			
			responseObj.setResponseTxt("failed");
			
			logger.info("LoginEmailId >> " + objBean.getLoginEmailId() );
			logger.info("Token >> " + objBean.getToken() );
			
			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.getNavigationOptions() );
				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);
			}

			List<OrganisationInfo> tsrbObj = (List<OrganisationInfo>) stRepo.findAllByOrderByOrganisationNameAsc();
			responseObj.setList(tsrbObj);
			
			responseObj.setResponseTxt("success");
		        
		}catch(Exception e) {
			e.getStackTrace();
		}
		
		
		return responseObj;
	}
	

	
	

	
	
}
