package com.agilex.healthcare.schedulingmanager.mdws;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.agilex.healthcare.schedulingmanager.datalayer.EmrDataLayer;

/**
 * Helper class to retrieve the list of clinic specialty values for a site from MDWS. The clinic specialty values are 
 * retrieved on the first access to getSpecialtyMap().
 *
 * This class is optimized to retrieve the clinic specialty list only once for the scope of the object. If the list
 * of clinic specialties ever changes, the application must be restarted.
 */
@Service
@Scope(value = "singleton")
public class MdwsClinicSpecialtyHelper {
    private final Log logger = LogFactory.getLog(MdwsClinicSpecialtyHelper.class);

    @Resource(name = "emrDataLayer")
    private EmrDataLayer emrDataLayer;

    private Map<String, String> specialtyMap = Collections.checkedMap(new HashMap<String, String>(), String.class, String.class);

    private String siteCode;

    /**
     * Return the list of Clinic Specialty values from MDWS for a given site. This class is optimized
     *
     * @param siteCode The target site.
     * @return
     */
    synchronized public Map<String,String> getSpecialtyMap(final String siteCode) {
        // Client requested a new site so clear the list and save the code
        if (null != this.siteCode && !this.siteCode.equals(siteCode)) {
            specialtyMap.clear();
        }

        if (specialtyMap.size() == 0) {
            this.specialtyMap.putAll(emrDataLayer.getSpecialties(siteCode));
            this.siteCode = siteCode;
            logger.info(String.format("Retrieved %d specialty codes from MDWS.", specialtyMap.size()));
        }
        return specialtyMap;
    }
}
