package vik.sakshum.sakshumweb.server.common;

import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.nio.channels.Channels;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;

import vik.sakshum.sakshumweb.client.bean.BloodDonorProfileBean;
import vik.sakshum.sakshumweb.client.constants.Constants;
import vik.sakshum.sakshumweb.server.jdo.BloodDonor;
import vik.sakshum.sakshumweb.server.jdo.BloodDonorCount;
import vik.sakshum.sakshumweb.server.jdo.PMF;
import vik.sakshum.sakshumweb.server.jdo.PocInfo;
import vik.sakshum.sakshumweb.server.jdo.StateDistrict;
import vik.sakshum.sakshumweb.server.jdo.StateDistrictCity;
import vik.sakshum.sakshumweb.utilities.CustomMethods;
import vik.sakshum.sakshumweb.utilities.SendMail;

import com.google.gdata.client.DocumentQuery;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.data.media.MediaSource;

import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileReadChannel;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.files.GSFileOptions.GSFileOptionsBuilder;

public class CommonServiceCode {
	private static final Logger log = Logger.getLogger(CommonServiceCode.class.getName());
	private PersistenceManager pm;
	
	@SuppressWarnings("unchecked")
	public List<String> getCity(String state, String distt) throws Exception {
		log.finest("start of GeoDataServiceImpl getCity started at::" + System.currentTimeMillis());
		List<String> cityList = new ArrayList<String>();
		try{
			state= state.toLowerCase();
			distt = distt.toLowerCase();
			log.info("state is:::::" + state + " distt:::::::" + distt);
			pm = PMF.get().getPersistenceManager();
			
			String query = "select from " + StateDistrictCity.class.getName() +
	        " where stateName == '" + state.toLowerCase() + "' && disttName == '" + distt.toLowerCase() + "'";
			
			
	        List<StateDistrictCity> cities = (List<StateDistrictCity>) pm.newQuery(query).execute();
	        if(cities.size() ==0)
	        	return cityList;
	        
	        Iterator<StateDistrictCity> cityItr = cities.iterator();
	        while(cityItr.hasNext()){
	        	StateDistrictCity stateDistrictCity = cityItr.next();
				cityList.add(CustomMethods.initCap(stateDistrictCity.getCityName()));
			}
	  }catch(Exception e) {
          log.severe("Exception in execute of getCity");
          log.severe("Exception class is :" + 
                             e.getClass().getName());
          log.severe("Exception is :" + e.getMessage());
          e.printStackTrace();
          throw new Exception(e.getMessage() + "\nException while fetching a city." +
          		"Please report it immediately.");
      } finally {
          try{
        	  if(pm != null && pm.isClosed() == false)
        		  pm.close();
          }catch(Exception e){
          	e.printStackTrace();
          	log.severe("Exception in finally of execute of getCity");
          	log.severe("Exception class is :" + 
                                 e.getClass().getName());
          	log.severe("Exception is :" + e.getMessage());
              throw new Exception(e.getMessage() + "Unable to close persistence manager");
          }
      }
		
		return cityList;
	}
	
	@SuppressWarnings("unchecked")
	public List<String> getDistt(String state) throws Exception{
		log.info("start of CommonServiceCode getDistt started at::" + System.currentTimeMillis());
		List<String> disttList = new ArrayList<String>();
		try{
			log.info("state is:::::" + state);
			pm = PMF.get().getPersistenceManager();
			
			//#248 added order by clause
			String query = "select from " + StateDistrict.class.getName() +
	        " where stateName == '" + state.toLowerCase() + "' order by disttName";
	        log.info("query is:" + query);
			List<StateDistrict> districts = (List<StateDistrict>) pm.newQuery(query).execute();
	        
	        if(districts.size() ==0)
	        	return disttList;
	        	
	        Iterator<StateDistrict> distItr = districts.iterator();
	         disttList.clear();
		     while(distItr.hasNext()){
				StateDistrict stateDistt = distItr.next();
				disttList.add(CustomMethods.initCap(stateDistt.getDisttName()));
			}
	  }catch(Exception e) {
          log.severe("Exception in execute of getDistt");
          log.severe("Exception class is :" + 
                             e.getClass().getName());
          log.severe("Exception is :" + e.getMessage());
          e.printStackTrace();
          throw new Exception(e.getMessage() + "\nException while fetching a distt." +
          		"Please report it immediately.");
      } finally {
    	  try{
    		  if(pm != null && pm.isClosed() == false)
    			  pm.close();
          	log.info("end of CommonServiceCode getDistt started at::" + System.currentTimeMillis());
          }catch(Exception e){
          	e.printStackTrace();
          	log.severe("Exception in finally of execute of getDistt");
          	log.severe("Exception class is :" + 
                                 e.getClass().getName());
          	log.severe("Exception is :" + e.getMessage());
          	throw new Exception(e.getMessage() + "Unable to close persistence manager");
          }
      }
      return disttList;
	}//end getDistt
	
	/**
	 *  #327 improved logging and exception handling
	 *  This method does the operation increase or decrease by updateCount
	 * @param state
	 * @param distt
	 * @param bloodGroup
	 * @param city
	 * @param area
	 * @param operation
	 * @param updateCount
	 */
	public void updateBloodDonorCount(String state, String distt, String bloodGroup,
			String city, String area, String operation, int updateCount, PersistenceManager pm) throws Exception{
		try{
			log.info("start of CommonServiceCode:updateBloodDonorCount with state:"+state + " district:" +
					distt + " city:" + city + " area:" + area + " bloodgroup:" + bloodGroup + " operation:" +
					operation + " updatecount:" + updateCount);
	        String query = "select from " + BloodDonorCount.class.getName() + " where distt == '" + distt.toLowerCase() +
	        "' && city== '" + city.toLowerCase() + "' && area=='" + area.toLowerCase() +
	        "' && bloodGroup=='" + bloodGroup + "'";
	        @SuppressWarnings("unchecked")
			List<BloodDonorCount> bloodDonorCountList= (List<BloodDonorCount>) pm.newQuery(query).execute();
	        //if blood donor count is required to increment
	        if(operation.equalsIgnoreCase("increase")){
	        	log.info("Blood donor count is required to be increamented ");
	            if(bloodDonorCountList == null || bloodDonorCountList.size() == 0){
	            	log.info("No blood donor in this blood gorup exists in same state, district, city and area" +
	            			" so creating a new location record");
	            	BloodDonorCount bloodDonorCount = new BloodDonorCount(state, distt, city, area, bloodGroup, updateCount);
	            	pm.makePersistent(bloodDonorCount);
	            }else{
	          	  if(bloodDonorCountList.size() > 1){
	          		  //exceptional situation email to admin
	          		log.info("Sending exception email as blood donor count list size is:" + bloodDonorCountList.size());
	          		  sendException("There are more than one record exists for the combination of state:" +
	          				  state + ": distt:" +
	          				  distt + ": city:" + city + ": area:" + area + ": blood Group:" + bloodGroup + ". Please investigate class" +
	          				  		" BloodDonorRegisterServiceImpl for method DonorRegister.");
	          		throw new Exception("There are marked invalid blood donors but corresponding blood donor count" +
    		  		" record does not exist.");
	          	  }
	          	log.info("A blood donor in this blood gorup exists in same state, district, city and area" +
				" so updating the existing location record");          	  
	          	  Long bloodDonorCountId = bloodDonorCountList.get(0).getBloodDonorCountSeq();
	          	  BloodDonorCount donorCount = pm.getObjectById(BloodDonorCount.class,bloodDonorCountId);
	          	  donorCount.setDonorCount(bloodDonorCountList.get(0).getDonorCount() + updateCount);
	            }
	            log.info("blood donor count increamented successfully");
	        }else{
	        	log.info("Blood donor count is required to be decremented ");
	            if(bloodDonorCountList == null || bloodDonorCountList.size() == 0 ||
	            		bloodDonorCountList.size() > 1){
	      		  	 log.info("Sending exception email as blood donor count list size is:" + bloodDonorCountList.size());
	            	 //exceptional situation email to admin
	        		  sendException("There are null or less than one record or more than 1 records exists for the combination of state:" +
	        				  state + ": distt:" +
	        				  distt + ": city:" + city + ": area:" + area + ": blood Group:" + bloodGroup + ". Please investigate class" +
	        				  		" BloodDonorRegisterServiceImpl for method DonorRegister.");
	        		  log.info("Exception email send. Throwing exception");
	        		  throw new Exception("There are marked invalid blood donors but corresponding blood donor count" +
	        		  		" record does not exist.");
	            }else{
	            	 log.info("decreasing the blood donor count");
	            	 long currentCount = bloodDonorCountList.get(0).getDonorCount(); 
	            	 log.info("current blood donor count is:" + currentCount);
	            	 Long bloodDonorCountId = bloodDonorCountList.get(0).getBloodDonorCountSeq();
	        		 BloodDonorCount donorCount = pm.getObjectById(BloodDonorCount.class,bloodDonorCountId);
	            	 if(currentCount - updateCount == 0){
	            		 //we need to remove the entity row from BloodDonorCount to prevent showing 0 on find blood donor page
	            		 log.info("Blood donor being deleted is the last blood donor in the area so deleting the record");
	            		 pm.deletePersistent(donorCount);
	            	 }
	            	 else{
	            		 log.info("There are more than 1 blood donor in the same area so decreasing the blood donor count");
	            		 donorCount.setDonorCount(currentCount - updateCount);
	            	 }
	            		 
	            }
	        	log.info("blood donor count decreamented successfully");
	        }
			
		}catch(Exception e){
			e.printStackTrace();
			log.severe(e.getMessage() + "\nUnable to update blood donor count");
			throw new Exception(e.getMessage() + "\n" + "Unable to update blood donor count");
		}
        
	}//end updateBloodDonorCount
	
	public void sendException(String message){
		log.finest("start of BloodDonorRegisterServiceImpl sendException started at::" + System.currentTimeMillis());
		try{
			  String mailSubject = "Exceptional situation occured!!!";
	            String mailBody = "Hello Admin<br/>  Please act now. <br/> Reported Issue:" + message;
	            
	            String[] mailTo = Constants.supportAdmin;
	           
	            SendMail.send(Constants.bugsAdmin,mailTo, null, mailSubject, mailBody);
	            System.out.println("mail sent");
	    }catch(Exception e){
	           //intentionally do nothing. so that mail sending failure should not
	           //stop subscription process
	           log.warning(e.getMessage() + ":: Class::" + e.getClass());
	           }
		log.finest("end of BloodDonorRegisterServiceImpl sendException ended at::" + System.currentTimeMillis());
	}
	
	/**
	 * 
	 * @param state
	 * @param distt
	 * @param bloodGroup
	 * @param city
	 * @param area
	 * @param updateCount
	 * @param pm
	 */
	public void setBloodDonorCount(String state, String distt, String bloodGroup,
			String city, String area, long updateCount, PersistenceManager pm){
        String query = "select from " + BloodDonorCount.class.getName() + " where distt == '" + distt.toLowerCase() +
        "' && city== '" + city.toLowerCase() + "' && area=='" + area.toLowerCase() +
        "' && bloodGroup=='" + bloodGroup + "'";
        
        @SuppressWarnings("unchecked")
		List<BloodDonorCount> bloodDonorCountList= (List<BloodDonorCount>) pm.newQuery(query).execute();
        if(bloodDonorCountList == null || bloodDonorCountList.size() == 0){
        	 log.info("set value for blood donor count for new record"); 
             BloodDonorCount bloodDonorCount = new BloodDonorCount(state, distt, city, area, bloodGroup, updateCount);
             pm.makePersistent(bloodDonorCount);
        }else
        {
        	Long bloodDonorCountId = bloodDonorCountList.get(0).getBloodDonorCountSeq();
        	BloodDonorCount donorCount = pm.getObjectById(BloodDonorCount.class,bloodDonorCountId);  
        	//#292 fixed blood donor count 
        	if(updateCount ==0){
        		 log.info("Unnecessary entry exist with 0 donors so deleting it");
        		 pm.deletePersistent(donorCount);
        	 }else{
             	log.info("set new value for blood donor count for existing record");          	  
            	donorCount.setDonorCount(updateCount); 
        	 }           		
        }
            log.info("blood donor count updated successfully");
	}//end updateBloodDonorCount
	
	/**
	 * #288 moved this method to the common code section   
	 * @param bloodDonors
	 * @return
	 */
	public List<BloodDonorProfileBean> processBloodDonorAdminData(
				List<BloodDonor> bloodDonors) {
			List<BloodDonorProfileBean> donorData = new ArrayList<BloodDonorProfileBean>();
			Iterator<BloodDonor> itr = bloodDonors.iterator();
			while(itr.hasNext()){
				BloodDonor bloodDonor = itr.next();
				//#345 added reference String
				BloodDonorProfileBean findBloodDonorResultBean = 
					new BloodDonorProfileBean(bloodDonor.getBloodDonorSeq(), 
							CustomMethods.initCap(bloodDonor.getFirstName()),
							CustomMethods.initCap(bloodDonor.getLastName()),
							bloodDonor.getBloodGroup(),
							bloodDonor.getGender(),
							bloodDonor.getEmailId(),
							bloodDonor.getCellNumber(),
							bloodDonor.getHomeNumber(),
							bloodDonor.getOfficeNumber(),
							bloodDonor.getPrimaryAddress(),
							CustomMethods.initCap(bloodDonor.getCity()),
							bloodDonor.getPinCode(),
							CustomMethods.initCap(bloodDonor.getArea()),
							CustomMethods.initCap(bloodDonor.getDistrict()),
							CustomMethods.initCap(bloodDonor.getState()),
							CustomMethods.initCap(bloodDonor.getCountry()), bloodDonor.getReference());

				//#303 added comments
				findBloodDonorResultBean.setComments(bloodDonor.getComments());
				//#328 added reason field
				findBloodDonorResultBean.setReason(bloodDonor.getReason());
				//#364 added subscription field
				findBloodDonorResultBean.setSubscribe(bloodDonor.getIsSubscribed());
				donorData.add(findBloodDonorResultBean);
			}
			return donorData;
		}

	@SuppressWarnings("unchecked")
	/**
	 * #300 code refactored to find POCs id of the area where blood donor is registered
	 */
	public List<PocInfo> findPossiblePocs(PersistenceManager pm, int minPocCount, String country,
			String state, String district, String city, String area) {
        log.info("Trying to find POCs in same area");
        //#278 removed isDefault==false clause from all the poc find queries.
        //#313 skip area search if it is not specified by donor
        String query=null;
        List<PocInfo> pocInfoList = new ArrayList<PocInfo>();
        if(!area.equals(Constants.NOT_SPECIFIED)){
          log.info("as area is not specified so skipping area search");
          //#371 added isActive clause
          query = "select from " + PocInfo.class.getName() + " where city == \"" + city.toLowerCase() + "\"" +
          			" && country == \"" + country.toLowerCase() + "\" && state == \"" + state.toLowerCase() +
          			"\" && district ==\"" + district.toLowerCase() + "\" && area == \"" + area.toLowerCase() + "\" && isActive == true";
          log.info("SQL query is:" + query);
          pocInfoList = (List<PocInfo>) pm.newQuery(query).execute();
        }

          List<PocInfo> pocDefaultInfoList = new ArrayList<PocInfo>();
          if(pocInfoList.size() < minPocCount){
        	  log.info(pocInfoList.size() + " No POCs found in same area, city, district, state. Finding in same city");
              //#371 added isActive clause
        	  query =  "select from " + PocInfo.class.getName() + " where city == \"" + city.toLowerCase() + "\"" +
    			" && country == \"" + country.toLowerCase() + "\" && state == \"" + state.toLowerCase() +
      			"\" && district ==\"" + district.toLowerCase() + "\" && isActive == true";
        	  log.info("SQL query is:" + query);
        	  pocInfoList = (List<PocInfo>) pm.newQuery(query).execute();
        	  
        	  if(pocInfoList.size() < minPocCount){
	        	  log.info(pocInfoList.size() + " no of POC found in same city, district, state. Finding in same district");
	              //#371 added isActive clause
	        	  query =  "select from " + PocInfo.class.getName() + " where country == \"" + country.toLowerCase() + 
	        	  "\" && state == \"" + state.toLowerCase() +
          			"\" && district ==\"" + district.toLowerCase() + "\" && isActive == true";
	        	  log.info("SQL query is:" + query);
	        	  pocInfoList = (List<PocInfo>) pm.newQuery(query).execute();
	        	  
	        	  if(pocInfoList.size() < minPocCount){
		        	  log.info(pocInfoList.size() + " no of POC found in same  district, state. Finding in same state");
		              //#371 added isActive clause
		        	  query =  "select from " + PocInfo.class.getName() + " where country == \"" + country.toLowerCase() + 
		        	  "\" && state == \"" + state.toLowerCase() + "\" && isActive == true";
		        	  log.info("SQL query is:" + query);
		        	  pocInfoList = (List<PocInfo>) pm.newQuery(query).execute();
		        	  
		        	  if(pocInfoList.size() < minPocCount){
		        		  log.info(pocInfoList.size() + " number of POC found which is less than min pocs(" + minPocCount + ") required. Need to show default POCs");
		        		 //#254 integrate default pocs to poc system
		                  //#371 added isActive clause
		        		  query = "select from " + PocInfo.class.getName() + " where isDefault == true && isActive == true";
		        		 log.info("SQL query is:" + query);
		        		 pocDefaultInfoList = (List<PocInfo>) pm.newQuery(query).execute();
		        	  }
		          }
	          }
          }

          if(pocInfoList.size() == 0 && pocDefaultInfoList.size() == 0)
        	  return pocInfoList;
          
          List<PocInfo> mergedPocList = mergePocListWithDefaultPocs(pocInfoList, pocDefaultInfoList, minPocCount);
          log.info("Found " + pocInfoList.size() + " matching POCs and " +  pocDefaultInfoList.size() + " default POCs to the donor search region.");
          return mergedPocList;
	}//end findPossiblePocs
	
	/**
	 * #254 integrates default POCs in to the system
	 * This method creates a single list by merged found matching POCs and 
	 * required default POCs
	 * @param pocInfoList
	 * @param pocDefaultInfoList
	 * @return
	 */
	private List<PocInfo> mergePocListWithDefaultPocs(List<PocInfo> pocInfoList,
			List<PocInfo> pocDefaultInfoList, int minPocCount) {
		
		//check if matched POCs are less than MIN_POC_COUNT
		if(pocInfoList.size() >= minPocCount)
			return pocInfoList;
		
		List<PocInfo> mergedList = new ArrayList<PocInfo>();
		mergedList.addAll(pocInfoList);
	
		Iterator<PocInfo> itr = pocDefaultInfoList.iterator();
		while(itr.hasNext()){
			PocInfo poc = itr.next();
			//#308 skipped already added POCs
			if(mergedList.contains(poc)){
				log.info(poc.getFirstName() + " with id:" + poc.getPocId() + " already added so skipping.");
				continue;
			}
			
			mergedList.add(poc);
			if(mergedList.size() >= minPocCount )
				break;
		}

		return mergedList;
	}//end mergePocListWithDefaulPocs
	
	
	public String createCertificate(Long donorId, String donorName) throws Exception{
		log.info("Start of getGoogleDoc");
	//	try{
			String emailMsgTxt = getGoogleDoc("BloodDonorCertificate");
			emailMsgTxt = emailMsgTxt.replace("[DONOR_ID]", donorId.toString());
			emailMsgTxt = emailMsgTxt.replace("[DONOR_NAME]", donorName);
			
			Date dt = new Date();
			 SimpleDateFormat formatter =
			            new SimpleDateFormat("dd/MMM/yyyy");
			 String today = formatter.format(dt);
			emailMsgTxt = emailMsgTxt.replace("[DONATION_DATE]", today);
		//	log.info(emailMsgTxt);
		
			System.out.println("Starting google storage with exceptions");
			// Get the file service
			FileService fileService = FileServiceFactory.getFileService();

			/**
			 * Set up properties of your new object
			 * After finalizing objects, they are accessible
			 * through Cloud Storage with the URL:
			 * http://commondatastorage.googleapis.com/my_bucket/my_object
			 */
			GSFileOptionsBuilder optionsBuilder = new GSFileOptionsBuilder()
			  .setBucket("blood")
			  .setKey("1234567")
			  .setAcl("public-read")
			  .setMimeType("text/html");//.setUserMetadata("date-created", "092011", "owner", "Jon");


			// Create your object
			AppEngineFile writableFile = fileService.createNewGSFile(optionsBuilder.build());
			
			// Open a channel for writing
			boolean lockForWrite = true; // Do you want to exclusively lock this object?
			FileWriteChannel writeChannel = fileService.openWriteChannel(writableFile, lockForWrite);
			// For this example, we write to the object using the PrintWriter
			PrintWriter out = new PrintWriter(Channels.newWriter(writeChannel, "UTF8"));
			out.println("The woods are lovely and deep.");
			out.println("But I have promises too keep.");

			// Close the object without finalizing.
			out.close();
			
			// Finalize the object
			writeChannel.closeFinally();
			System.out.println("Completed writing to google storage");
			return emailMsgTxt;
			
/*		}catch(Exception e){
        	e.printStackTrace();
			log.severe("Exception in finally of execute of getGoogleDoc");
        	log.severe("Exception class is :" + 
                               e.getClass().getName());
        	log.severe("Exception is :" + e.getMessage());
            throw new Exception(e.getMessage() + " Issue while reading document from google docs");

		}finally{
		log.info("End of getGoogleDoc");
		}*/
	}
	
	/**
	 * #356 common code to read google doc
	 * @param title
	 * @return
	 * @throws Exception
	 */
	public String getGoogleDoc(String title) throws Exception{
		log.info("Start of getGoogleDoc");
		StringBuffer emailBody = null;
	//	try{
			GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();  
			oauthParameters.setOAuthConsumerKey(Constants.CONSUMER_KEY);  
			oauthParameters.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);  
			oauthParameters.setOAuthToken(Constants.ACCESS_TOKEN); 
			oauthParameters.setOAuthTokenSecret(Constants.ACCESS_TOKEN_SECRET);  
			DocsService client = new DocsService("sakshum-YourAppName-v1");  
			client.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());  
			URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/");  
			DocumentQuery dquery = new DocumentQuery(feedUrl);
			dquery.setTitleQuery(title);
			dquery.setTitleExact(true);
			dquery.setMaxResults(10);
			DocumentListFeed resultFeed = client.getFeed(dquery, DocumentListFeed.class);
			log.info("feed size:" + resultFeed.getEntries().size());
			if(resultFeed.getEntries().size() != 1){
				log.info("More than one document is found with same title.");
				return null;
			}
			emailBody = new StringBuffer("");
			for (DocumentListEntry entry : resultFeed.getEntries()) {  
				String docId = entry.getDocId();
				String docType = entry.getType();
				URL exportUrl =
				              new URL("https://docs.google.com/feeds/download/" + docType
				                  + "s/Export?docID=" + docId + "&exportFormat=html");
				MediaContent mc = new MediaContent();
				mc.setUri(exportUrl.toString());
				
				MediaSource ms = client.getMedia(mc);
				InputStream inStream = null;
				try {
				    inStream = ms.getInputStream();
				    int c;
				    while ((c = inStream.read()) != -1) {
				    	emailBody.append((char)c);
				    }
				  } finally {
				    if (inStream != null) {
				      inStream.close();
				    }
				  }					
			}
			
		/*}catch(Exception e){
        	e.printStackTrace();
			log.severe("Exception in finally of execute of getGoogleDoc");
        	log.severe("Exception class is :" + 
                               e.getClass().getName());
        	log.severe("Exception is :" + e.getMessage());
            throw new Exception(e.getMessage() + " Issue while reading document from google docs");

		}*/
		log.info("End of getGoogleDoc");
		return emailBody.toString();
	}//end getGoogleDoc

}