// tspcall.cpp

#include "pch.h"
#include "tspcall.h"

CtspCall::CtspCall(CtspLine* pLine, HTAPICALL htCall)
:   m_pLine(pLine),
    m_dwCallState(LINECALLSTATE_UNKNOWN),
    m_dwCallStateDetail(0),
    m_htCall(htCall)
{
}

CtspCall::~CtspCall()
{
    Drop();
}

CtspLine* CtspCall::GetLine()
{
    return m_pLine;
}

void CtspCall::Drop()
{
    if( m_dwCallState != LINECALLSTATE_IDLE )
    {
        SetCallState(LINECALLSTATE_IDLE);
        m_pLine->m_nActiveCalls--;
    }
}

void CtspCall::SetCallState(
    DWORD   dwCallState,
    DWORD   dwCallStateDetail)
{
    if( dwCallState != m_dwCallState )
    {
        m_pLine->Event(m_pLine->m_htLine,
                       m_htCall,
                       LINE_CALLSTATE,
                       m_dwCallState = dwCallState,
                       m_dwCallStateDetail = dwCallStateDetail);
    }
}

DWORD CtspCall::GetCallState()
{
    return m_dwCallState;
}

LONG CtspCall::StartDial(
    HINSTANCE               hinst,
    HPROVIDER               hProvider,
    DWORD                   dwRequestID,
    const wchar_t*          pwszAddress,
    const LINEDIALPARAMS&   dp)
{
    // Can't dial if we're already doing something else
    if( (m_dwCallState != LINECALLSTATE_UNKNOWN) &&
        (m_dwCallState != LINECALLSTATE_CONNECTED) )
    {
        return LINEERR_OPERATIONUNAVAIL;
    }

    LONG        tr = 0;
    size_t      cbAddress = wcslen(pwszAddress) + 1;
    size_t      cbData = sizeof(TSPUIDATA) + sizeof(LINEDIALPARAMS) + cbAddress;
    TSPUIDATA*  pData = (TSPUIDATA*)(new BYTE[cbData]);
    if( pData )
    {
        // Data passed back from UI
        pData->dwRequestID = dwRequestID;
        pData->pCall = this;

        // Copy LINEDIALPARAMS for UI
        LINEDIALPARAMS* pdp = (LINEDIALPARAMS*)((BYTE*)pData + sizeof(*pData));
        *pdp = dp;

        // Copy dial string for UI
        char*   pszAddress = (char*)((BYTE*)pData + sizeof(*pData) + sizeof(LINEDIALPARAMS));
        wcstombs(pszAddress, pwszAddress, cbAddress);

        wchar_t pwszFileName[MAX_PATH+1];
        TSPI_providerUIIdentify(pwszFileName);

        TUISPICREATEDIALOGINSTANCEPARAMS    params;
        params.dwRequestID = dwRequestID;
        params.hdDlgInst = (HDRVDIALOGINSTANCE)this;
        params.htDlgInst = 0;   // Set by TAPI
        params.lpszUIDLLName = pwszFileName;
        params.lpParams = (void*)pData;
        params.dwSize = cbData;

        // Send message to UI portion via TUISPI_providerGenericDialog
        m_pLine->Event((HTAPILINE)hProvider, 0, LINE_CREATEDIALOGINSTANCE, (DWORD)&params);

        if( params.htDlgInst )
        {
            m_pLine->m_nActiveCalls++;
        }
        else
        {
            tr = LINEERR_OPERATIONFAILED;
        }
    }
    else
    {
        tr = LINEERR_NOMEM;
    }

    delete[] pData;
    return tr;
}

