// Class cVaxPhoneCall

function OnVaxPhoneIncomingCallBlickTimer()
{
    m_objPhoneCall.OnBlinkTick();
}

function cVaxPhoneCall()
{
    var m_hBlinkTimer = null;

    let m_hMediaRecorder = null;
    let m_aRecordedChunks = [];
    
    this.OnLoadPage = function ()
    {
        m_objVaxWebPhoneLib.SetEventMainSIP(OnInitialized, OnUnInitialized, null, null, null, null);

        m_objVaxWebPhoneLib.SetEventServerWebRTC(OnTryingToConnectServerWebRTC, OnFailedToConnectServerWebRTC, OnSuccessToConnectServerWebRTC, OnConnectionClosedServerWebRTC);

        m_objVaxWebPhoneLib.SetEventCall(null, OnHungupCall, null);
        m_objVaxWebPhoneLib.SetEventDialCall(OnDialCallStarted, OnDialingCall, OnDialCallFailed, OnDialCallConnected, null, null, null, null);

        m_objVaxWebPhoneLib.SetEventIncomingCall(OnIncomingCallStarted, OnIncomingCallEnded, null, null, OnIncomingCallConnected, null, null, null, null);
        m_objVaxWebPhoneLib.SetEventHold(OnTryingToHold, OnFailedToHold, OnSuccessToHold, OnTryingToUnHold, OnFailedToUnHold, OnSuccessToUnHold);

        m_objVaxWebPhoneLib.SetEventMediaWebRTC(OnAttachedAudioSendWebRTC, OnAttachedAudioRecvWebRTC, OnAttachedVideoSendWebRTC, OnAttachedVideoRecvWebRTC);

        this.ReadPhoneNo();
	}

    /////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////

    function OnInitialized()
    {
        m_hBlinkTimer = null;
        m_objMainHtml.SetBtnCallText("Dial");
    }

    function OnUnInitialized()
    {
        m_objMainHtml.SetBtnCallText("Dial");
        m_objMainHtml.SetBtnHoldText("Hold");

        BlinkStop();

        while (ListIncomingCall.length > 0)
            ListIncomingCall.remove(0);

        StopMediaRecordWebRTC();
    }

    function OnHungupCall()
    {
        m_objMainHtml.SetBtnCallText("Dial");
        m_objMainHtml.SetBtnHoldText("Hold");

        m_objMainHtml.AddPhoneStatusLog("Call ended by the other party");

        StopMediaRecordWebRTC();
    }

    //////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////

    function OnAttachedAudioSendWebRTC(hStream) {
        // StartAudioRecordWebRTC(hStream);
    }

    function OnAttachedAudioRecvWebRTC(hStream) {
        //  StartAudioRecordWebRTC(hStream);
    }

    function OnAttachedVideoSendWebRTC(hStream) {
        // StartVideoRecordWebRTC(hStream);
    }

    function OnAttachedVideoRecvWebRTC(hStream) {
        //StartVideoRecordWebRTC(hStream);
    }

    /////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////

    this.BtnDial_onclick = function ()
    {
        if (m_objMainHtml.GetBtnCallText() == "Hangup")
        {
            m_objMainHtml.SetBtnCallText("Dial");

            m_objVaxWebPhoneLib.DisconnectCall();
            StopMediaRecordWebRTC();

            return;
        }

        if (EditPhoneNo.value == "") 
        {
            return;
        }
                
		SavePhoneNo();

        m_objVaxWebPhoneLib.DialCall("", "", EditPhoneNo.value);
        
        m_objMainHtml.SetBtnCallText("Hangup");
	}
    
    /////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////

    this.BtnHold_onclick = function ()
    {
        if (m_objMainHtml.GetBtnHoldText() == "UnHold")
        {
            m_objMainHtml.SetBtnHoldText("Hold");

            m_objVaxWebPhoneLib.UnHoldCall();
            return;
        }

        m_objMainHtml.SetBtnHoldText("UnHold");
        m_objVaxWebPhoneLib.HoldCall();
    }

    /////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////

    this.BtnAccept_onclick = function ()
    {
        if (ListIncomingCall.selectedIndex == -1) return;

        var sJson = ListIncomingCall.options[ListIncomingCall.selectedIndex].value;
        var objValue = JSON.parse(sJson);

        sCallId = objValue.CallId;
        
        if (!m_objVaxWebPhoneLib.AcceptCall(sCallId))
            return;
                
        BlinkStop();
        RemoveIncomingCall(sCallId);
    }

    /////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////

    this.BtnReject_onclick = function ()
    {
        if (ListIncomingCall.selectedIndex == -1) return;

        var sJson = ListIncomingCall.options[ListIncomingCall.selectedIndex].value;
        var objValue = JSON.parse(sJson);

        sCallId = objValue.CallId;
                        
        m_objVaxWebPhoneLib.RejectCall(sCallId);

        BlinkStop();
        RemoveIncomingCall(sCallId);
    }
        
    /////////////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////
	
	function SavePhoneNo()
	{
    	SetCookie('DialPhoneNo', EditPhoneNo.value);
	}

	this.ReadPhoneNo = function()
	{	
		var Value = GetCookie('DialPhoneNo');
		
    	if (Value != null)
        	EditPhoneNo.value = Value;
	}
                
    /////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////

    function OnDialCallStarted(sCallerName, sCallerId, sDialNo)
    {
        m_objMainHtml.AddPhoneStatusLog("Dialing: " + sDialNo);
    }

    function OnDialingCall(nStatusCode, sReasonPhrase)
    {
        m_objMainHtml.AddPhoneStatusLog("Response: " + sReasonPhrase);
    }

    function OnDialCallFailed(nStatusCode, sReasonPhrase, sContact)
    {
        m_objMainHtml.AddPhoneStatusLog("Response: " + sReasonPhrase);
    }

    function OnDialCallConnected()
    {
        m_objMainHtml.AddPhoneStatusLog("Successfully connected");
    }

    /////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////
    
    this.BtnClearPhoneLog_onclick = function ()
    {
        ListPhoneLog.value = "";
    }

    /////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////

    function OnDialCallStarted(sCallerName, sCallerId, sDialNo)
    {
        m_objMainHtml.AddPhoneStatusLog("Dialing: " + sDialNo);
    }

    function OnDialingCall(nStatusCode, sReasonPhrase)
    {
        m_objMainHtml.AddPhoneStatusLog("Response: " + sReasonPhrase);
    }

    function OnDialCallFailed(nStatusCode, sReasonPhrase, sContact)
    {
        m_objMainHtml.AddPhoneStatusLog("Response: " + sReasonPhrase);
    }

    function OnDialCallConnected()
    {
        m_objMainHtml.SetBtnCallText("Hangup");
        m_objMainHtml.AddPhoneStatusLog("Successfully connected");
    }

    /////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////

    /////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////

    function OnIncomingCallStarted(sCallId, sCallerName, sCallerId, sDialNo)
    {
        if (FindIncomingCall(sCallId) != -1) return;

        if (sCallerName.length != 0)
            AddIncomingCall("NAME: " + sCallerName + ", CLI: " + sCallerId, sCallId);
        else
            AddIncomingCall("NAME: Unknown" + ", CLI: " + sCallerId, sCallId);

        BlinkStart();
    }

    function OnIncomingCallEnded(sCallId)
    {
        nItemIndex = FindIncomingCall(sCallId);
        if (nItemIndex == -1) return;

        BlinkStop();
        RemoveIncomingCall(sCallId);
    }

    function OnIncomingCallConnected()
    {
        m_objMainHtml.SetBtnCallText("Hangup");
        m_objMainHtml.AddPhoneStatusLog("Successfully connected");
    }

    /////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////

    function AddIncomingCall(sCallerId, sCallId)
    {
        var objValue = { CallId: sCallId };
        var sJson = JSON.stringify(objValue);

        ListIncomingCall.options[ListIncomingCall.options.length] = new Option(sCallerId, sJson);

        if (ListIncomingCall.selectedIndex == -1 && ListIncomingCall.length > 0)
            ListIncomingCall.selectedIndex = 0;

    }

    function FindIncomingCall(sCallId)
    {
        for (nItemIndex = 0; nItemIndex < ListIncomingCall.length; nItemIndex++)
        {
            var sJson = ListIncomingCall.options[nItemIndex].value;
            var objValue = JSON.parse(sJson);

            if (objValue.CallId == sCallId)
                return nItemIndex;
        }

        return -1;
    }

    function RemoveIncomingCall(sCallId)
    {
        nItemIndex = FindIncomingCall(sCallId);
        if (nItemIndex == -1) return;

        ListIncomingCall.remove(nItemIndex);

        if (ListIncomingCall.selectedIndex == -1 && ListIncomingCall.length > 0)
            ListIncomingCall.selectedIndex = 0;
    }
        
    /////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////

    this.BtnForwardCall_onclick = function ()
    {
        if (BtnForwardCall.value == "Disable")
        {
            BtnForwardCall.value = "Enable";
            m_objVaxWebPhoneLib.ForwardCall(false, EditForwardCallPhoneNo.value);
            return;
        }

        if (EditForwardCallPhoneNo.value == "")
        {
            ShowDialog("Please enter a phone number.");
            return;
        }

        BtnForwardCall.value = 'Disable';

        m_objVaxWebPhoneLib.ForwardCall(true, EditForwardCallPhoneNo.value);
    }

    this.CheckDonotDisturb_onclick = function ()
    {
        if (CheckDonotDisturb.checked)
        {
            m_objVaxWebPhoneLib.DonotDisturb(true);
            return;
        }

        m_objVaxWebPhoneLib.DonotDisturb(false);
    }

    this.CheckMuteMic_onclick = function ()
    {
        if (CheckMuteMic.checked)
        {
            m_objVaxWebPhoneLib.MuteMic(true);
            return;
        }

        m_objVaxWebPhoneLib.MuteMic(false);
    }

    /////////////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////
        
    function BlinkStart()
    {
        BlinkStop();

        m_hBlinkTimer = setInterval("OnVaxPhoneIncomingCallBlickTimer()", 500);
    }

    function BlinkStop()
    {
        if (m_hBlinkTimer != null) {
            clearInterval(m_hBlinkTimer);
            m_hBlinkTimer = null;
        }

        document.getElementById("PhoneTabLink").style.color = "";
    }

    this.OnBlinkTick = function ()
    {
        LinkText = document.getElementById("PhoneTabLink");
        LinkText.style.color = (LinkText.style.color == 'red' ? 'grey' : 'red');
    }

    /////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////

    function OnTryingToConnectServerWebRTC()
    {
        m_objMainHtml.AddPhoneStatusLog("VaxServerWebRTC: Trying to connect");
    }

    function OnFailedToConnectServerWebRTC()
    {
        m_objMainHtml.AddPhoneStatusLog("VaxServerWebRTC: Failed to connect");
    }

    function OnSuccessToConnectServerWebRTC()
    {
        m_objMainHtml.AddPhoneStatusLog("VaxServerWebRTC: Successfully connected");
    }

    function OnConnectionClosedServerWebRTC()
    {
        m_objMainHtml.AddPhoneStatusLog("VaxServerWebRTC: Disconnected");
    }

    /////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////

    function OnTryingToHold() {
        m_objMainHtml.AddPhoneStatusLog("Trying to hold");
    }

    function OnFailedToHold() {
        m_objMainHtml.AddPhoneStatusLog("Failed to hold");
    }

    function OnSuccessToHold()
    {
        m_objMainHtml.SetBtnHoldText("UnHold");
        m_objMainHtml.AddPhoneStatusLog("Success to hold");
    }

    function OnTryingToUnHold() {
        m_objMainHtml.AddPhoneStatusLog("Trying to unhold");
    }

    function OnFailedToUnHold() {
        m_objMainHtml.AddPhoneStatusLog("Failed to unhold");
    }

    function OnSuccessToUnHold()
    {
        m_objMainHtml.SetBtnHoldText("Hold");
        m_objMainHtml.AddPhoneStatusLog("Success to unhold");
    }

    /////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////

    function StartAudioRecordWebRTC(hStream)
    {
        const audioTracks = hStream.getAudioTracks();
        const audioOnlyStream = new MediaStream(audioTracks);

        m_hMediaRecorder = new MediaRecorder(audioOnlyStream, { mimeType: "audio/webm" });

        m_hMediaRecorder.ondataavailable = e => {
            if (e.data.size > 0) m_aRecordedChunks.push(e.data);
        };

        m_hMediaRecorder.onstop = () => {
            const blob = new Blob(m_aRecordedChunks, { type: "audio/webm" });
            const url = URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = url;
            a.download = "VaxWebPhoneAudio.webm";
            a.click();
            m_aRecordedChunks = [];
        };

        m_hMediaRecorder.start();
    }

    function StartVideoRecordWebRTC(hStream)
    {
        m_hMediaRecorder = new MediaRecorder(hStream, { mimeType: "video/webm" });

        m_aRecordedChunks = [];

        m_hMediaRecorder.ondataavailable = e => {
            if (e.data.size > 0) m_aRecordedChunks.push(e.data);
        };

        m_hMediaRecorder.onstop = () => {
            const blob = new Blob(m_aRecordedChunks, { type: "video/webm" });
            const url = URL.createObjectURL(blob);

            const a = document.createElement("a");
            a.href = url;
            a.download = "VaxWebPhoneVideo.webm";
            a.click();

            m_aRecordedChunks = [];
        };

        m_hMediaRecorder.start();
        console.log("Video+Audio recording started");
    }

    function StopMediaRecordWebRTC()
    {
        if (m_hMediaRecorder == null)
            return;

        m_hMediaRecorder.stop();
        m_hMediaRecorder = null;
    }
};