/*****************************************************************************
 * Â© 2014 Avaya Inc. All rights reserved.
 ****************************************************************************/
package com.avaya.zephyr.services.sample_services.ClickToCall;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

import com.avaya.asm.datamgr.DMFactory;
import com.avaya.collaboration.businessdata.api.NoAttributeFoundException;
import com.avaya.collaboration.util.logger.Logger;
import com.avaya.zephyr.platform.dao.ClusterAttributeDAO;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;

public final class RequestProcessorImpl implements RequestProcessor
{
    private static final String DOMAIN_DELIMITER_AT = "@";
    private final ClickToCall callMeCallYou;
    private final ClusterAttributeDAO clusterAttributeDAO;
    private final Logger logger;

    public RequestProcessorImpl()
    {
        this(new ClickToCallImpl(), (ClusterAttributeDAO) DMFactory.getInstance().getDataMgr(
                ClusterAttributeDAO.class), Logger.getLogger(RequestProcessorImpl.class));
    }

    RequestProcessorImpl(final ClickToCall callMeCallYou, final ClusterAttributeDAO clusterAttributeDAO,
            final Logger logger)
    {
        this.callMeCallYou = callMeCallYou;
        this.clusterAttributeDAO = clusterAttributeDAO;
        this.logger = logger;
    }

    /**
     * post body format example:
     * first=3403@avaya.com&amp;second=3404@avaya.com&amp;calling=3405@avaya.com. We are
     * expecting but not enforcing UTF-8 format.
     * 
     * @throws UnsupportedEncodingException Specified encoding is not supported in body
     * @throws NoAttributeFoundException No SipDefaultDomain cluster attribute
     */
    @Override
    public void processHttpPost(final String postBody) throws UnsupportedEncodingException,
            NoAttributeFoundException
    {
        logger.finer("processHttpPost ENTER");

        final String body = URLDecoder.decode(postBody, "UTF-8");
        final Map<String, String> keyValues = Splitter.on("&")
                .withKeyValueSeparator("=")
                .split(body);
        final String firstParty = keyValues.get("first");
        final String secondParty = keyValues.get("second");
        final String callingId = keyValues.get("calling");
        final String display = keyValues.get("display");
        
        if(Strings.nullToEmpty(firstParty).trim().isEmpty())
        {
            throw new IllegalArgumentException("First Party is invalid");
        }
        
        if(Strings.nullToEmpty(secondParty).trim().isEmpty())
        {
            throw new IllegalArgumentException("Second Party is invalid");
        }
        
        if(Strings.nullToEmpty(callingId).trim().isEmpty())
        {
            throw new IllegalArgumentException("Calling Identity is invalid");
        }
        
        callMeCallYou.makeCall(buildPhoneNumber(firstParty), buildPhoneNumber(secondParty),
                buildPhoneNumber(callingId),display);

        logger.finer("processHttpPost EXIT");
    }
    @Override
    public String getHandle(final String phoneNumber)
    {
        if (phoneNumber.contains(DOMAIN_DELIMITER_AT))
        {
            final int delimeterIndex = phoneNumber.indexOf(DOMAIN_DELIMITER_AT);
            final String handle = phoneNumber.substring(0, delimeterIndex);

            return handle;
        }
        return phoneNumber;
    }
    @Override
    public String buildPhoneNumber(final String phoneNumber) throws NoAttributeFoundException
    {
        return getHandle(phoneNumber) + DOMAIN_DELIMITER_AT + getDomain(phoneNumber);
    }
    @Override
    public String getDomain(final String phoneNumber) throws NoAttributeFoundException
    {
        if (phoneNumber.contains(DOMAIN_DELIMITER_AT))
        {
            final int delimeterIndex = phoneNumber.indexOf(DOMAIN_DELIMITER_AT);
            final String domain = phoneNumber.substring(delimeterIndex + 1, phoneNumber.length());

            return domain;
        }
        return clusterAttributeDAO.getClusterAttribute("SIPDefaultDomain");
    }
}
