/****************************************************************************
* Copyright Avaya Inc., All Rights Reserved.
* THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Avaya Inc.
* The copyright notice above does not evidence any actual or intended publication of such source code.
* Some third-party source code components may have been modified from their original versions by Avaya Inc.
* The modifications are Copyright Avaya Inc., All Rights Reserved.
* Avaya Confidential & Restricted. May not be distributed further without written permission of
* the Avaya owner.
****************************************************************************/
package com.avaya.zephyr.services.sample_services.Authorization.TaskDashboard.provider;

import java.net.InetAddress;
import java.net.UnknownHostException;

import com.avaya.asm.core.AsmConstants.TRANSPORT;
import com.avaya.asm.datamgr.AssetDM;
import com.avaya.asm.datamgr.DMFactory;
import com.avaya.asm.datamgr.objectapi.AssetLinkInfo;
import com.avaya.collaboration.util.logger.Logger;
import com.google.common.base.Strings;

final class EndpointProviderImpl implements EndpointProvider
{
    private String endpoint;
    private final DMFactory dmFactory;
    private final Logger logger;

    EndpointProviderImpl()
    {
        this(DMFactory.getInstance(),Logger.getLogger(EndpointProviderImpl.class));
    }

    EndpointProviderImpl(final DMFactory dmFactory,final Logger logger)
    {
        this.dmFactory = dmFactory;
        this.logger = logger;
    }

    @Override
    public String getResourceEndpoint()
    {
        return endpoint;
    }

    @Override
    public void buildResourceEndpoint()
    {
        String assetIp = null;
        AssetDM assetDM = (AssetDM) dmFactory.getDataMgr(AssetDM.class);
        if (assetDM != null)
        {
            // Set transport as TRANSPORT.TLS for Https connection
            final AssetLinkInfo localAsset = assetDM.getAssetLinkInfo(TRANSPORT.TCP);
            if (localAsset != null)
            {
                try
                {
                    InetAddress trafficInterface = InetAddress.getByName(localAsset.getEntityIp());
                    assetIp = trafficInterface.getHostAddress();
                }
                catch (UnknownHostException e)
                {
                    logger.error("Error Reading Asset Ip ", e);
                }
            }
        }
        logger.info("buildResourceEndpoint" + assetIp);
        if (Strings.isNullOrEmpty(assetIp))
        {
            logger.error("Asset IP is null");
            return;
        }
        endpoint = "https://" + assetIp + "/services/TaskRepository/ws/sample/tasks";
        logger.info("buildResourceEndpoint endPoint" + endpoint);
    }
}
