package gov.va.med.pharmacy.web.administration;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.json.JsonSanitizer;

import gov.va.med.pharmacy.persistence.managepharmacy.ManagePharmacyFilter;
import gov.va.med.pharmacy.persistence.model.PharmacyEntity;
import gov.va.med.pharmacy.persistence.report.VisnSelectModel;
import gov.va.med.pharmacy.persistence.service.PharmacyService;
import gov.va.med.pharmacy.persistence.service.TrackMessageService;
import gov.va.med.pharmacy.utility.ESAPIValidationType;
import gov.va.med.pharmacy.utility.ESAPIValidator;
import gov.va.med.pharmacy.web.ResponseMessage;
import gov.va.med.pharmacy.web.administration.managepharmacy.PharmacyForm;
import net.rossillo.spring.web.mvc.CacheControl;
import net.rossillo.spring.web.mvc.CachePolicy;

@Controller
@RequestMapping(value = "/managePharm")
public class PharmacyManagementController {

	private static final org.apache.logging.log4j.Logger LOG = org.apache.logging.log4j.LogManager.getLogger(PharmacyManagementController.class);
	
	@Autowired
	private PharmacyService pharmacyService;
	
	@Autowired
	private TrackMessageService trackMessageService;

	
	final private String[] DISALLOWED_FIELDS = new String[]{"updatedDate", "createdDate"};
	
	//TO-DO update with fields not to bind from form.
	@InitBinder
	public void initBinderFields(WebDataBinder binder) {
	    binder.setDisallowedFields(DISALLOWED_FIELDS);
	}

	
	@RequestMapping(value = "/main")
	public String getMainPage(HttpServletRequest request) {

		return "managepharmacy.homepage";
	}

	@RequestMapping(value = "/getPharmacyList",  method = RequestMethod.GET)	
	public ModelAndView getPharmacyList(HttpServletRequest request, @RequestParam("json") String json) throws JsonParseException, JsonMappingException, IOException {

		ModelAndView mav = new ModelAndView(new org.springframework.web.servlet.view.json.MappingJackson2JsonView());
		
		String jsonString = JsonSanitizer.sanitize(json); // Sanitize the JSON coming from client
		
		ObjectMapper jsonMapper = new ObjectMapper();

		ManagePharmacyFilter managePharmacyFilter = jsonMapper.readValue(jsonString, ManagePharmacyFilter.class);

		List<PharmacyEntity> pharmacyList = pharmacyService.find(managePharmacyFilter);
		
		mav.addObject("items", pharmacyList);

		return mav;
	}
	
	
	@RequestMapping(value = "/editPharmacy/{ncpdpID}",  method = RequestMethod.GET)	
	public ModelAndView editPharmacy(HttpServletRequest request, @PathVariable(value="ncpdpID") String NCPDPId) throws JsonParseException, JsonMappingException, IOException {

		//System.out.println("NCPDP Id is: "+NCPDPId);
		
		ModelAndView view = new ModelAndView("editpharmacy.homepage");
		
		PharmacyEntity pharmacyInfo = pharmacyService.findByNCPDPId(NCPDPId);
				
		view.addObject("pharmacyInfo",pharmacyInfo );
		
		Map<String, String> statesMap = getStatesHashMap();
		
        Map<Long, String> specialityMap = getSpecialityHashMap();
		
		Map<String, String> serviceLevelMap = getServiceLevelHashMap();

		view.addObject("statesMap",statesMap );
		
        view.addObject("specialityMap",specialityMap );
		
		view.addObject("serviceLevelMap",serviceLevelMap );
		
		return view;
		
	}
	
	@RequestMapping(value = "/updatePharmacy",  method = RequestMethod.POST)	
	public ModelAndView updatePharmacy(HttpServletRequest request,@Valid @ModelAttribute("pharmacyEditForm") PharmacyForm pharmacyForm, BindingResult bindingResult) throws  IOException {

		LOG.info("Trying to persist pharmacy information.");
		
		ResponseMessage responseMessage = new ResponseMessage();
		List<String> errorsList = new ArrayList<String>();
		
		// validation
		
		 if (bindingResult.hasErrors()) {
			 List<ObjectError> errors = bindingResult.getAllErrors();
			 
			 for (ObjectError objectError : errors) {
				 errorsList.add(objectError.getDefaultMessage());
		 }
		
       
        }
				
		ModelAndView view = new ModelAndView("editpharmacy.homepage");
		
		// we need to use find by id as NCPDP ID can change and findByNCPDPId wont work.
		PharmacyEntity pharmacyInfo = null;
		
			
		try {
		
			// needed for fortify scan issue for access db violation.
			String pharmacyId = ESAPIValidator.validateStringInput(pharmacyForm.getPharmacyId(), ESAPIValidationType.ACCESS_CONTROL_DB);
			
			pharmacyInfo = pharmacyService.findById(Long.valueOf(pharmacyId));	
				
				
			Date updatedDate = new Date();
			
			SimpleDateFormat originalDateFormmatter = new SimpleDateFormat("MM/dd/yyyy",   Locale.US);
						
			Date activeStartDate = originalDateFormmatter.parse(pharmacyForm.getActiveStartTime());
			
			Date activeEndDate = originalDateFormmatter.parse(pharmacyForm.getActiveEndTime());
			
			pharmacyInfo.setVaStationId(pharmacyForm.getVaStationId());
			pharmacyInfo.setServiceLevel(pharmacyForm.getServiceLevel());
			pharmacyInfo.setActiveStartTime(activeStartDate);
			pharmacyInfo.setActiveEndTime(activeEndDate);
			pharmacyInfo.setSpecialtyId(Long.valueOf(pharmacyForm.getSpecialtyId()));
			pharmacyInfo.setNcpdpId(pharmacyForm.getNcpdpId());
				
			pharmacyInfo.setStateLicenseNumber(pharmacyForm.getStateLicenseNumber());
			pharmacyInfo.setMedicareNumber(pharmacyForm.getMedicareNumber());
			pharmacyInfo.setMedicaidNumber(pharmacyForm.getMedicaidNumber());
			pharmacyInfo.setPpoNumber(pharmacyForm.getPpoNumber());
			pharmacyInfo.setPayerId(pharmacyForm.getPayerId());
			pharmacyInfo.setBinLocationNumber(pharmacyForm.getBinLocationNumber());
			pharmacyInfo.setDeaNumber(pharmacyForm.getDeaNumber());
			pharmacyInfo.setHin(pharmacyForm.getHin());
			pharmacyInfo.setSecondaryCoverage(pharmacyForm.getSecondaryCoverage());
			pharmacyInfo.setNaicCode(pharmacyForm.getNaicCode());
			pharmacyInfo.setPromotionNumber(pharmacyForm.getPromotionNumber());
			pharmacyInfo.setStoreName(pharmacyForm.getStoreName());
			pharmacyInfo.setStoreNumber(pharmacyForm.getStoreNumber());
			pharmacyInfo.setPharmacistLastName(pharmacyForm.getPharmacistLastName());
			pharmacyInfo.setPharmacistFirstName(pharmacyForm.getPharmacistFirstName());
			pharmacyInfo.setPharmacistMiddleName(pharmacyForm.getPharmacistMiddleName());
			pharmacyInfo.setPharmacistSuffix(pharmacyForm.getPharmacistSuffix());
			pharmacyInfo.setPharmacistPrefix(pharmacyForm.getPharmacistPrefix());
			pharmacyInfo.setPharmacistAgentLastName(pharmacyForm.getPharmacistAgentLastName());
			pharmacyInfo.setPharmacistAgentFirstName(pharmacyForm.getPharmacistAgentFirstName());
			pharmacyInfo.setPharmacistAgentMiddleName(pharmacyForm.getPharmacistAgentMiddleName());
			pharmacyInfo.setPharmacistAgentSuffix(pharmacyForm.getPharmacistAgentSuffix());
			pharmacyInfo.setPharmacistAgentPrefix(pharmacyForm.getPharmacistAgentPrefix());
			pharmacyInfo.setPharmacyAddressLine1(pharmacyForm.getPharmacyAddressLine1());
			pharmacyInfo.setPharmacyAddressLine2(pharmacyForm.getPharmacyAddressLine2());
			pharmacyInfo.setPharmacyCity(pharmacyForm.getPharmacyCity());
			pharmacyInfo.setPharmacyState(pharmacyForm.getPharmacyState());
			pharmacyInfo.setPharmacyZipcode(pharmacyForm.getPharmacyZipcode());
			pharmacyInfo.setTwentyFourHourFlag(pharmacyForm.getTwentyFourHourFlag());
			pharmacyInfo.setCrossStreet(pharmacyForm.getCrossStreet());
			pharmacyInfo.setEmail(pharmacyForm.getEmail());
			pharmacyInfo.setPharmacyPhoneNumber(pharmacyForm.getPharmacyPhoneNumber());
			pharmacyInfo.setPharmacyFaxNumber(pharmacyForm.getPharmacyFaxNumber());
			pharmacyInfo.setUpdatedDate(updatedDate);		
			pharmacyInfo.setVisn(Long.valueOf(pharmacyForm.getVisn()));
			pharmacyInfo.setDivisionName(pharmacyForm.getDivisionName());
			pharmacyInfo.setInboundErxEnabled(Long.valueOf(pharmacyForm.getPharmacyEnabledDisabled()));
			
			if( (StringUtils.isNotBlank(pharmacyForm.getNpi())) && (StringUtils.isNumeric(pharmacyForm.getNpi()))){
				
				pharmacyInfo.setNpi(Long.valueOf(pharmacyForm.getNpi()));
			}
			
			
			if(!bindingResult.hasErrors() ) {
			
		    // get logged in user.
			Authentication  authentication = SecurityContextHolder.getContext().getAuthentication();	
			
			if(authentication!=null){
				
				String userName = (String)authentication.getPrincipal();
				pharmacyInfo.setUpdatedBy(userName);
			}
					
		    pharmacyService.updatePharmacyInfo(pharmacyInfo);
		    
		    // TBD
		    // This is done for dojo date widgets to show dates properly after update.
		    //pharmacyInfo = pharmacyService.findById(Long.valueOf(pharmacyForm.getPharmacyId()));
		 
			}
			
		} catch (HibernateException e) {
			
			e.printStackTrace();
			
			Throwable  cause = e.getCause();
			
			if(cause instanceof ConstraintViolationException){
				
				
				String constraintName = ((ConstraintViolationException) cause).getConstraintName();
				
				if(constraintName.contains("NCPDP_ID")){
				
					errorsList.add("Please use unique value for NCPDP ID.");
				}
				
				if(constraintName.contains("DIVISION_NAME")){
					
					errorsList.add("Please use unique value for Division Name.");
				}
				
				if(constraintName.contains("NPI")){
					
					errorsList.add("Please use unique value for NPI.");
				}
				
				
			}
			else{
				
				errorsList.add("Update Failed. Unable to save record. Please contact production support.");
			}
		}
		catch (Exception e) {
			
			e.printStackTrace();			
			
			errorsList.add("Update Failed. Unable to save record. Please contact production support.");
			
			
		  }
		
		
		responseMessage.setErrorMessage(errorsList);
		
		// set success message only if everything is successful.		
		if( responseMessage.getErrorMessage().isEmpty()){
			
			responseMessage.setSuccessMessage("Pharmacy information updated successfully.");	
		}
		
	    
		view.addObject("pharmacyInfo",pharmacyInfo );
		
		Map<String, String> statesMap = getStatesHashMap();
		
		Map<Long, String> specialityMap = getSpecialityHashMap();
		
		Map<String, String> serviceLevelMap = getServiceLevelHashMap();
		
		view.addObject("statesMap",statesMap );
		
		view.addObject("specialityMap",specialityMap );
		
		view.addObject("serviceLevelMap",serviceLevelMap );
		
		view.addObject("data",responseMessage );
		
		
		return view;	
		
	}

	
	
	
	
	@RequestMapping(value = "/getVisnSelect", method = RequestMethod.GET, produces = "application/json")
	@CacheControl(policy = {CachePolicy.NO_CACHE})
	@ResponseBody
	public List<VisnSelectModel> getVisnSelect(HttpServletRequest request)
			throws JsonParseException, JsonMappingException, IOException {
		

		List<VisnSelectModel> visnSelectModelList = new ArrayList<VisnSelectModel>();
		
		VisnSelectModel visnSelectModel = new VisnSelectModel();
		visnSelectModel.setId("");
		visnSelectModel.setLabel("All");
		visnSelectModelList.add(visnSelectModel);

		visnSelectModelList.addAll(trackMessageService.getVisns());
		
		return visnSelectModelList;
	}
	
	
	
	
	
	private Map<String, String> getServiceLevelHashMap() {
		
		Map<String, String> serviceLevelMap = new LinkedHashMap<String, String>();
		
		serviceLevelMap.put("1", "New Rx");
		serviceLevelMap.put("2", "Refill");
		serviceLevelMap.put("4", "Change");
		serviceLevelMap.put("8", "RxFill");
		serviceLevelMap.put("16", "Cancel");
		serviceLevelMap.put("32", "MedHistory");
		serviceLevelMap.put("64", "Eligibility");
		serviceLevelMap.put("128", "Not Used");
		serviceLevelMap.put("256", "Resupply");
		serviceLevelMap.put("512", "Census");
		serviceLevelMap.put("1024", "CCR");
		serviceLevelMap.put("2048", "Controlled Substance (EPCS)");
		
		return serviceLevelMap;
	}

	private Map<Long, String> getSpecialityHashMap() {
		Map<Long, String> specialityMap = new LinkedHashMap<Long, String>(); 
		
		specialityMap.put(new Long(1), "Mail Order Pharmacy");
		specialityMap.put(new Long(2), "Fax Pharmacy");
		specialityMap.put(new Long(8), "Retail Pharmacy");
		specialityMap.put(new Long(16), "Speciality Pharmacy");
		specialityMap.put(new Long(32), "Long-Term Care Pharmacy");
		specialityMap.put(new Long(64), "24 Hour Pharmacy");
		return specialityMap;
	}

	private Map<String, String> getStatesHashMap() {
		Map<String, String> statesMap = new LinkedHashMap<String, String>();
		
		statesMap.put("AL","Alabama");
		statesMap.put("AK","Alaska");
		statesMap.put("AZ","Arizona");
		statesMap.put("AR","Arkansas");
		statesMap.put("CA","California");
		statesMap.put("CO","Colorado");
		statesMap.put("CT","Connecticut");
		statesMap.put("DE","Delaware");
		statesMap.put("DC","District Of Columbia");
		statesMap.put("FL","Florida");
		statesMap.put("GA","Georgia");
		statesMap.put("HI","Hawaii");
		statesMap.put("ID","Idaho");
		statesMap.put("IL","Illinois");
		statesMap.put("IN","Indiana");
		statesMap.put("IA","Iowa");
		statesMap.put("KS","Kansas");
		statesMap.put("KY","Kentucky");
		statesMap.put("LA","Louisiana");
		statesMap.put("ME","Maine");
		statesMap.put("MD","Maryland");
		statesMap.put("MA","Massachusetts");
		statesMap.put("MI","Michigan");
		statesMap.put("MN","Minnesota");
		statesMap.put("MS","Mississippi");
		statesMap.put("MO","Missouri");
		statesMap.put("MT","Montana");
		statesMap.put("NE","Nebraska");
		statesMap.put("NV","Nevada");
		statesMap.put("NH","New Hampshire");
		statesMap.put("NJ","New Jersey");
		statesMap.put("NM","New Mexico");
		statesMap.put("NY","New York");
		statesMap.put("NC","North Carolina");
		statesMap.put("ND","North Dakota");
		statesMap.put("OH","Ohio");
		statesMap.put("OK","Oklahoma");
		statesMap.put("OR","Oregon");
		statesMap.put("PA","Pennsylvania");
		statesMap.put("RI","Rhode Island");
		statesMap.put("SC","South Carolina");
		statesMap.put("SD","South Dakota");
		statesMap.put("TN","Tennessee");
		statesMap.put("TX","Texas");
		statesMap.put("UT","Utah");
		statesMap.put("VT","Vermont");
		statesMap.put("VA","Virginia");
		statesMap.put("WA","Washington");
		statesMap.put("WV","West Virginia");
		statesMap.put("WI","Wisconsin");
		statesMap.put("WY","Wyoming");
		return statesMap;
	}

	@RequestMapping(value = "/addPharmacy",  method = RequestMethod.POST)	
	public ModelAndView newPharmacy(HttpServletRequest request) throws IOException {

		ModelAndView view = new ModelAndView("addpharmacy.homepage");
		
		Map<String, String> statesMap = getStatesHashMap();
		
        Map<Long, String> specialityMap = getSpecialityHashMap();
		
		Map<String, String> serviceLevelMap = getServiceLevelHashMap();
		
		view.addObject("statesMap",statesMap );
		
        view.addObject("specialityMap",specialityMap );
		
		view.addObject("serviceLevelMap",serviceLevelMap );
		
		return view;
		
	}
	
	@RequestMapping(value = "/addNewPharmacy",  method = RequestMethod.POST)	
	public ModelAndView addNewPharmacy(HttpServletRequest request,@Valid @ModelAttribute("pharmacyAddForm") PharmacyForm pharmacyForm, BindingResult bindingResult) throws  IOException {

		LOG.info("Trying to persist pharmacy information.");
		
		ResponseMessage responseMessage = new ResponseMessage();
		List<String> errorsList = new ArrayList<String>();
		
		// validation
		
		boolean hasErrors = false;
		
		 if (bindingResult.hasErrors()) {
			 List<ObjectError> errors = bindingResult.getAllErrors();
			 
			 for (ObjectError objectError : errors) {
				 errorsList.add(objectError.getDefaultMessage());
		 }
		
       
			 hasErrors = true;
        }
				
		ModelAndView view = null;
		
		
		
		// we need to use find by id as NCPDP ID can change and findByNCPDPId wont work.
		PharmacyEntity pharmacyInfo = new PharmacyEntity();
		
			
		try {
		
				
			Date updatedDate = new Date();
			
			pharmacyInfo.setVaStationId(pharmacyForm.getVaStationId());
			pharmacyInfo.setServiceLevel(pharmacyForm.getServiceLevel());
			pharmacyInfo.setActiveStartTime(new Date());
			pharmacyInfo.setActiveEndTime(new Date());
			pharmacyInfo.setSpecialtyId(Long.valueOf(pharmacyForm.getSpecialtyId()));
			pharmacyInfo.setNcpdpId(pharmacyForm.getNcpdpId());
				
			pharmacyInfo.setStateLicenseNumber(pharmacyForm.getStateLicenseNumber());
			pharmacyInfo.setMedicareNumber(pharmacyForm.getMedicareNumber());
			pharmacyInfo.setMedicaidNumber(pharmacyForm.getMedicaidNumber());
			pharmacyInfo.setPpoNumber(pharmacyForm.getPpoNumber());
			pharmacyInfo.setPayerId(pharmacyForm.getPayerId());
			pharmacyInfo.setBinLocationNumber(pharmacyForm.getBinLocationNumber());
			pharmacyInfo.setDeaNumber(pharmacyForm.getDeaNumber());
			pharmacyInfo.setHin(pharmacyForm.getHin());
			pharmacyInfo.setSecondaryCoverage(pharmacyForm.getSecondaryCoverage());
			pharmacyInfo.setNaicCode(pharmacyForm.getNaicCode());
			pharmacyInfo.setPromotionNumber(pharmacyForm.getPromotionNumber());
			pharmacyInfo.setStoreName(pharmacyForm.getStoreName());
			pharmacyInfo.setStoreNumber(pharmacyForm.getStoreNumber());
			pharmacyInfo.setPharmacistLastName(pharmacyForm.getPharmacistLastName());
			pharmacyInfo.setPharmacistFirstName(pharmacyForm.getPharmacistFirstName());
			pharmacyInfo.setPharmacistMiddleName(pharmacyForm.getPharmacistMiddleName());
			pharmacyInfo.setPharmacistSuffix(pharmacyForm.getPharmacistSuffix());
			pharmacyInfo.setPharmacistPrefix(pharmacyForm.getPharmacistPrefix());
			pharmacyInfo.setPharmacistAgentLastName(pharmacyForm.getPharmacistAgentLastName());
			pharmacyInfo.setPharmacistAgentFirstName(pharmacyForm.getPharmacistAgentFirstName());
			pharmacyInfo.setPharmacistAgentMiddleName(pharmacyForm.getPharmacistAgentMiddleName());
			pharmacyInfo.setPharmacistAgentSuffix(pharmacyForm.getPharmacistAgentSuffix());
			pharmacyInfo.setPharmacistAgentPrefix(pharmacyForm.getPharmacistAgentPrefix());
			pharmacyInfo.setPharmacyAddressLine1(pharmacyForm.getPharmacyAddressLine1());
			pharmacyInfo.setPharmacyAddressLine2(pharmacyForm.getPharmacyAddressLine2());
			pharmacyInfo.setPharmacyCity(pharmacyForm.getPharmacyCity());
			pharmacyInfo.setPharmacyState(pharmacyForm.getPharmacyState());
			pharmacyInfo.setPharmacyZipcode(pharmacyForm.getPharmacyZipcode());
			pharmacyInfo.setTwentyFourHourFlag(pharmacyForm.getTwentyFourHourFlag());
			pharmacyInfo.setCrossStreet(pharmacyForm.getCrossStreet());
			pharmacyInfo.setEmail(pharmacyForm.getEmail());
			pharmacyInfo.setPharmacyPhoneNumber(pharmacyForm.getPharmacyPhoneNumber());
			pharmacyInfo.setPharmacyFaxNumber(pharmacyForm.getPharmacyFaxNumber());
			
			pharmacyInfo.setCreatedDate(updatedDate);
			pharmacyInfo.setCreatedBy(null);
			pharmacyInfo.setUpdatedDate(updatedDate);		
		
			pharmacyInfo.setDivisionName(pharmacyForm.getDivisionName());
			pharmacyInfo.setInboundErxEnabled(Long.valueOf(pharmacyForm.getPharmacyEnabledDisabled()));
			
			

            if( (StringUtils.isNotBlank(pharmacyForm.getVisn())) && (StringUtils.isNumeric(pharmacyForm.getVisn()))){
				
				pharmacyInfo.setVisn(Long.valueOf(pharmacyForm.getVisn()));
			}
			
            if( (StringUtils.isNotBlank(pharmacyForm.getNpi())) && (StringUtils.isNumeric(pharmacyForm.getNpi()))){
				
				pharmacyInfo.setNpi(Long.valueOf(pharmacyForm.getNpi()));
			}
			
			
			if(!bindingResult.hasErrors() ) {
				
				 // get logged in user.
				Authentication  authentication = SecurityContextHolder.getContext().getAuthentication();	
				
				if(authentication!=null){
					
					String userName = (String)authentication.getPrincipal();
					pharmacyInfo.setUpdatedBy(userName);
					pharmacyInfo.setCreatedBy(userName);
				}	
			
		    pharmacyService.savePharmacyInfo(pharmacyInfo);
		    
			}
			else
			{
				hasErrors = true;
			}
			
		} catch (HibernateException e) {
			
			e.printStackTrace();
			
			Throwable  cause = e.getCause();
			
			if(cause instanceof ConstraintViolationException){
				
				
				String constraintName = ((ConstraintViolationException) cause).getConstraintName();
				
				if(constraintName.contains("NCPDP_ID")){
				
					errorsList.add("Please use unique value for NCPDP ID.");
				}
				
				if(constraintName.contains("DIVISION_NAME")){
					
					errorsList.add("Please use unique value for Division Name.");
				}
				
				if(constraintName.contains("NPI")){
					
					errorsList.add("Please use unique value for NPI.");
				}
				
				
			}
			else{
				
				errorsList.add("Add Failed. Unable to save record. Please contact production support.");
			}
			
			hasErrors = true;
		}
		catch (Exception e) {
			
			e.printStackTrace();			
			
			errorsList.add("Add Failed. Unable to save record. Please contact production support.");
			
			
		  }
		
		finally{
			
			if(hasErrors== true){
				view = new ModelAndView("addpharmacy.homepage");
			}
			else{
				view = new ModelAndView("managepharmacy.homepage");
			}
		}
		
		responseMessage.setErrorMessage(errorsList);
		
		// set success message only if everything is successful.		
		if( responseMessage.getErrorMessage().isEmpty()){
			
			responseMessage.setSuccessMessage("Pharmacy information added successfully.");	
		}
		
		view.addObject("pharmacyInfo",pharmacyInfo );
		
		Map<String, String> statesMap = getStatesHashMap();
		
		Map<Long, String> specialityMap = getSpecialityHashMap();
		
		Map<String, String> serviceLevelMap = getServiceLevelHashMap();

		view.addObject("statesMap",statesMap );
		
		view.addObject("specialityMap",specialityMap );
		
		view.addObject("serviceLevelMap",serviceLevelMap );
		
		view.addObject("data",responseMessage );
		
		
		return view;	
		
	}
	
}
