/*
 * The Kuali Financial System, a comprehensive financial management system for higher education.
 *
 * Copyright 2005-2016 The Kuali Foundation
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.kuali.kfs.module.external.kc.service.impl;

import org.kuali.kfs.module.external.kc.KcConstants;
import org.kuali.kfs.module.external.kc.businessobject.Agency;
import org.kuali.kfs.module.external.kc.service.ExternalizableLookupableBusinessObjectService;
import org.kuali.kfs.module.external.kc.util.GlobalVariablesExtractHelper;
import org.kuali.kfs.module.external.kc.webService.SponsorWebSoapService;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kra.external.sponsor.SponsorCriteriaDto;
import org.kuali.kra.external.sponsor.SponsorDTO;
import org.kuali.kra.external.sponsor.SponsorWebService;
import org.kuali.rice.core.api.config.property.ConfigurationService;
import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
import org.kuali.rice.krad.bo.BusinessObject;
import org.kuali.rice.krad.bo.ExternalizableBusinessObject;

import javax.xml.ws.WebServiceException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * This class was generated by Apache CXF 2.2.10
 * Thu Sep 30 05:29:28 HST 2010
 * Generated source version: 2.2.10
 */

public class SponsorServiceImpl implements ExternalizableLookupableBusinessObjectService {
    protected static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(SponsorServiceImpl.class);

    protected ConfigurationService configurationService;
    protected SponsorWebService sponsorWebService;

    @Override
    public ExternalizableBusinessObject findByPrimaryKey(Map primaryKeys) {
        SponsorDTO dto = this.getWebService().getSponsor((String) primaryKeys.get("agencyNumber"));
        return new Agency(dto);
    }

    @Override
    public Collection findMatching(Map fieldValues) {
        List<SponsorDTO> result = null;
        SponsorCriteriaDto criteria = new SponsorCriteriaDto();
        criteria.setSponsorCode((String) fieldValues.get("agencyNumber"));
        criteria.setCustomerNumber((String) fieldValues.get("customerNumber"));
        criteria.setSponsorName((String) fieldValues.get("reportingName"));
        criteria.setDunsPlusFourNumber((String) fieldValues.get("dunsPlusFourNumber"));
        criteria.setActive((String) fieldValues.get("active"));

        try {
            result = this.getWebService().getMatchingSponsors(criteria);
        } catch (WebServiceException ex) {
            GlobalVariablesExtractHelper.insertError(KcConstants.WEBSERVICE_UNREACHABLE, getConfigurationService().getPropertyValueAsString(KFSConstants.KC_APPLICATION_URL_KEY));
        }

        if (result == null) {
            return new ArrayList();
        } else {
            List<Agency> agencies = new ArrayList<Agency>();
            for (SponsorDTO dto : result) {
                agencies.add(new Agency(dto));
            }
            return agencies;
        }
    }

    @Override
    public List<? extends BusinessObject> getSearchResults(Map<String, String> fieldValues) {
        return new ArrayList(findMatching(fieldValues));
    }

    public ConfigurationService getConfigurationService() {
        return configurationService;
    }

    public void setConfigurationService(ConfigurationService configurationService) {
        this.configurationService = configurationService;
    }

    protected synchronized SponsorWebService getWebService() {
        if (sponsorWebService == null) {
            // first attempt to get the service from the KSB - works when KFS & KC share a Rice instance
            sponsorWebService = (SponsorWebService) GlobalResourceLoader.getService(KcConstants.Sponsor.SERVICE);

            // if we couldn't get the service from the KSB, get as web service - for when KFS & KC have separate Rice instances
            if (sponsorWebService == null) {
                LOG.warn("Couldn't get SponsorWebService from KSB, setting it up as SOAP web service - expected behavior for bundled Rice, but not when KFS & KC share a standalone Rice instance.");
                SponsorWebSoapService ss = null;
                try {
                    ss = new SponsorWebSoapService();
                } catch (MalformedURLException ex) {
                    LOG.error("Could not intialize SponsorWebSoapService: " + ex.getMessage());
                    throw new RuntimeException("Could not intialize SponsorWebSoapService: " + ex.getMessage());
                }
                sponsorWebService = ss.getSponsorWebServicePort();
            }
        }
        return sponsorWebService;
    }

    public void setWebService(SponsorWebService webService) {
        sponsorWebService = webService;
    }

}
