/**
 * Copyright 2008-2009 DRIVER PROJECT (ICM UW)
 * Original author: Marek Horst
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package eu.dnetlib.data.index.ws.ctx;

import org.apache.log4j.Logger;

import eu.dnetlib.common.profile.IndexServiceBody;
import eu.dnetlib.common.profile.Profile;
import eu.dnetlib.common.profile.utils.ProfileUnmarshaller;
import eu.dnetlib.data.index.ws.commons.profile.utils.IndexProfileUnMarshaller;
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpDocumentNotFoundException;
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;

/**
 * Maintains all global index context properties.
 * @author mhorst
 *
 */
public class GlobalIndexContext {
	
	protected static final Logger log = Logger.getLogger(GlobalIndexContext.class);
	
	/**
	 * IS-LU service.
	 */
	private ISLookUpService lookUpService;
	
	/**
	 * IndexService profile identifier.
	 */
	private String indexServiceProfId;
	
	/**
	 * Global index service status.
	 * Should be used in a synchronized way.
	 */
	private boolean readOnlyStatus = false;
	
	/**
	 * Flag for checking service read-only status on service startup.
	 */
	private boolean checkServiceStatusOnStartup;
	
	/**
	 * Spring init method.
	 * 
	 */
	public void init() {
//		checking read-only status at service startup
		try {
			setReadOnlyStatus(performReadOnlyStatusCheck());
		} catch (Exception e) {
			log.error("Exception occured during bean initialization",e);
		}
		
	}

	/**
	 * Retrieves current indexServiceProfile and checks its status.
	 * @return true if read-only status is set, otherwise false.
	 */
	private boolean performReadOnlyStatusCheck() {
		if (checkServiceStatusOnStartup) {
			String indexServiceProfile = null;
			try {
				indexServiceProfile = lookUpService.getResourceProfile(indexServiceProfId);
			} catch (ISLookUpDocumentNotFoundException e1) {
				String errorContent = "Exception occured when geting" +
						" index profile from IS. Profile identified by" +
						indexServiceProfId + " not found in IS Registry.";
				log.error(errorContent);
				return false;
			} catch (ISLookUpException e) {
				String errorContent = "Exception occured when geting" +
					" index profile from IS. " + e;
				log.error(errorContent);
				return false;
			}
			
			Profile profile = IndexProfileUnMarshaller.unmarshallIndexServiceResource(indexServiceProfile);
			if (profile==null || profile.getHeader()==null ||
					profile.getBody()==null || !(profile.getBody() instanceof IndexServiceBody)) {
				log.warn("Invalid indexServiceProfile content: "+indexServiceProfile + 
						"\n Global index service read-only status will be set to default: false");
				return false;
			} else {
				if (((IndexServiceBody)profile.getBody()).getIndexServiceStatus()!=null &&
						((IndexServiceBody)profile.getBody()).getIndexServiceStatus().getReadOnlyStatus()!=null) {
					Boolean status = ((IndexServiceBody)profile.getBody()).getIndexServiceStatus().getReadOnlyStatus();
					log.debug("setting new index service read-only status: "+status);
					return status;
				} else {
					log.warn("No service status found in indexServiceProfile content: " + indexServiceProfile + 
					"\n Global index service read-only status will be set to default: false");
					return false;
				}
			}
		} else {
			log.warn("Checking service status at startup is disabled! " +
					"Setting default read-only status to false.");
			return false;	
		}
	}
	
	/**
	 * Returns IS-LU service.
	 * @return IS-LU service
	 */
	public ISLookUpService getLookUpService() {
		return lookUpService;
	}

	/**
	 * Sets IS-LU service.
	 * @param lookUpService
	 */
	public void setLookUpService(ISLookUpService lookUpService) {
		this.lookUpService = lookUpService;
	}
	
	/**
	 * Returns global index service status.
	 * @return global index service status
	 */
	public synchronized boolean isReadOnlyStatus() {
		return readOnlyStatus;
	}

	/**
	 * Sets global index service status.
	 * @param readOnlyStatus
	 */
	public synchronized void setReadOnlyStatus(boolean readOnlyStatus) {
		this.readOnlyStatus = readOnlyStatus;
	}

	/**
	 * Returns flag for checking service read-only status on service startup.
	 * @return flag for checking service read-only status on service startup
	 */
	public boolean isCheckServiceStatusOnStartup() {
		return checkServiceStatusOnStartup;
	}

	/**
	 * Sets flag for checking service read-only status on service startup.
	 * @param checkServiceStatusOnStartup
	 */
	public void setCheckServiceStatusOnStartup(boolean checkServiceStatusOnStartup) {
		this.checkServiceStatusOnStartup = checkServiceStatusOnStartup;
	}

	/**
	 * Returns IndexService profile identifier.
	 * @return IndexService profile identifier
	 */
	public String getIndexServiceProfId() {
		return indexServiceProfId;
	}

	/**
	 * Sets IndexService profile identifier.
	 * @param indexServiceProfId
	 */
	public void setIndexServiceProfId(String indexServiceProfId) {
		this.indexServiceProfId = indexServiceProfId;
	}
	


}
