/*
 * Copyright (C) 2015 Ericsson AB. All rights reserved.
 * Copyright (C) 2016-2017 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer
 *    in the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name of Ericsson nor the names of its contributors
 *    may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"

#include "PeerConnectionBackend.h"

#if ENABLE(WEB_RTC)

#include "EventNames.h"
#include "JSRTCSessionDescription.h"
#include "MediaStream.h"
#include "RTCIceCandidate.h"
#include "RTCPeerConnection.h"
#include "RTCPeerConnectionIceEvent.h"
#include "RTCRtpReceiver.h"
#include "RTCSessionDescription.h"
#include <wtf/text/StringBuilder.h>

namespace WebCore {

#if !USE(LIBWEBRTC)
class NullRTCDataChannelHandler FINAL : public RTCDataChannelHandler {
public:
	NullRTCDataChannelHandler() { }
    virtual ~NullRTCDataChannelHandler() { }

    virtual void setClient(RTCDataChannelHandlerClient*) FINAL { }

    virtual bool sendStringData(const String&) FINAL { return false; }
    virtual bool sendRawData(const char*, size_t) FINAL { return false; }
    virtual void close() FINAL { }

    virtual size_t bufferedAmount() const FINAL { return 0; }
};

class NullPeerConnectionBackend FINAL : public PeerConnectionBackend {
	WTF_MAKE_FAST_ALLOCATED;
public:
	NullPeerConnectionBackend(RTCPeerConnection& peerConnection)
		: PeerConnectionBackend(peerConnection)
	{
	}
    virtual ~NullPeerConnectionBackend() { }

    virtual PassOwnPtr<RTCDataChannelHandler> createDataChannelHandler(const String&, const RTCDataChannelInit&) FINAL
	{
    	return adoptPtr(new NullRTCDataChannelHandler());
	}

    virtual RefPtr<RTCSessionDescription> localDescription() const FINAL { return nullptr; }
    virtual RefPtr<RTCSessionDescription> currentLocalDescription() const FINAL { return nullptr; }
    virtual RefPtr<RTCSessionDescription> pendingLocalDescription() const FINAL { return nullptr; }

    virtual RefPtr<RTCSessionDescription> remoteDescription() const FINAL { return nullptr; }
    virtual RefPtr<RTCSessionDescription> currentRemoteDescription() const FINAL { return nullptr; }
    virtual RefPtr<RTCSessionDescription> pendingRemoteDescription() const FINAL { return nullptr; }

    virtual void setConfiguration(MediaEndpointConfiguration&&) FINAL { }

    virtual void getStats(MediaStreamTrack*, RefPtr<DeferredPromise>&&) FINAL { }

    virtual Vector<RefPtr<MediaStream>> getRemoteStreams() const FINAL { return Vector<RefPtr<MediaStream>>(); }

    virtual RefPtr<RTCRtpReceiver> createReceiver(const String& transceiverMid, const String& trackKind, const String& trackId) FINAL { return nullptr; }
	virtual void replaceTrack(RTCRtpSender&, Ref<MediaStreamTrack>&&, PeerConnection::VoidPromise) FINAL { }

    virtual void emulatePlatformEvent(const String& action) FINAL { }

private:
    virtual void doCreateOffer(const RTCOfferOptions&) FINAL { }
    virtual void doCreateAnswer(const RTCAnswerOptions&) FINAL { }
    virtual void doSetLocalDescription(RTCSessionDescription&) FINAL { }
    virtual void doSetRemoteDescription(RTCSessionDescription&) FINAL { }
    virtual void doAddIceCandidate(RTCIceCandidate&) FINAL { }
    virtual void doStop() FINAL { }
};

static PassOwnPtr<PeerConnectionBackend> createPeerConnectionBackend(RTCPeerConnection& peerConnection)
{
    return adoptPtr(new NullPeerConnectionBackend(peerConnection));
}

CreatePeerConnectionBackend PeerConnectionBackend::create = createPeerConnectionBackend;
#endif

void PeerConnectionBackend::createOffer(const RTCOfferOptions& options, PeerConnection::SessionDescriptionPromise promise)
{
    ASSERT(!m_offerAnswerPromise);
    ASSERT(m_peerConnection.signalingState() != RTCSignalingState::Closed);

    m_offerAnswerPromise = WTFMove(promise);
    doCreateOffer(options);
}

void PeerConnectionBackend::createOfferSucceeded(const String& sdp)
{
    ASSERT(isMainThread());

    if (m_peerConnection.signalingState() == RTCSignalingState::Closed)
        return;

    ASSERT(m_offerAnswerPromise);
    (*m_offerAnswerPromise)->resolve(RTCSessionDescription::create(RTCSdpType::Offer, sdp).get());
    m_offerAnswerPromise = Nullopt;
}

void PeerConnectionBackend::createOfferFailed(const Exception& exception)
{
    ASSERT(isMainThread());

    if (m_peerConnection.signalingState() == RTCSignalingState::Closed)
        return;

    ASSERT(m_offerAnswerPromise);
    (*m_offerAnswerPromise)->reject(exception);
    m_offerAnswerPromise = Nullopt;
}

void PeerConnectionBackend::createAnswer(const RTCAnswerOptions& options, PeerConnection::SessionDescriptionPromise promise)
{
    ASSERT(!m_offerAnswerPromise);
    ASSERT(m_peerConnection.signalingState() != RTCSignalingState::Closed);

    m_offerAnswerPromise = WTFMove(promise);
    doCreateAnswer(options);
}

void PeerConnectionBackend::createAnswerSucceeded(const String& sdp)
{
    ASSERT(isMainThread());

    if (m_peerConnection.signalingState() == RTCSignalingState::Closed)
        return;

    ASSERT(m_offerAnswerPromise);
    (*m_offerAnswerPromise)->resolve(RTCSessionDescription::create(RTCSdpType::Answer, sdp).get());
    m_offerAnswerPromise = Nullopt;
}

void PeerConnectionBackend::createAnswerFailed(const Exception& exception)
{
    ASSERT(isMainThread());

    if (m_peerConnection.signalingState() == RTCSignalingState::Closed)
        return;

    ASSERT(m_offerAnswerPromise);
    (*m_offerAnswerPromise)->reject(exception);
    m_offerAnswerPromise = Nullopt;
}

static inline bool isLocalDescriptionTypeValidForState(RTCSdpType type, RTCSignalingState state)
{
    switch (state) {
    case RTCSignalingState::Stable:
        return type == RTCSdpType::Offer;
    case RTCSignalingState::HaveLocalOffer:
        return type == RTCSdpType::Offer;
    case RTCSignalingState::HaveRemoteOffer:
        return type == RTCSdpType::Answer || type == RTCSdpType::Pranswer;
    case RTCSignalingState::HaveLocalPranswer:
        return type == RTCSdpType::Answer || type == RTCSdpType::Pranswer;
    default:
        return false;
    };

    ASSERT_NOT_REACHED();
    return false;
}

void PeerConnectionBackend::setLocalDescription(RTCSessionDescription& sessionDescription, PeerConnection::VoidPromise promise)
{
    ASSERT(m_peerConnection.signalingState() != RTCSignalingState::Closed);

    if (!isLocalDescriptionTypeValidForState(sessionDescription.type(), m_peerConnection.signalingState())) {
        promise->reject(INVALID_STATE_ERR, ASCIILiteral("Description type incompatible with current signaling state"));
        return;
    }

    m_setDescriptionPromise = WTFMove(promise);
    doSetLocalDescription(sessionDescription);
}

void PeerConnectionBackend::setLocalDescriptionSucceeded()
{
    ASSERT(isMainThread());

    if (m_peerConnection.signalingState() == RTCSignalingState::Closed)
        return;

    ASSERT(m_setDescriptionPromise);

    (*m_setDescriptionPromise)->resolve(nullptr);
    m_setDescriptionPromise = Nullopt;
}

void PeerConnectionBackend::setLocalDescriptionFailed(const Exception& exception)
{
    ASSERT(isMainThread());

    if (m_peerConnection.signalingState() == RTCSignalingState::Closed)
        return;

    ASSERT(m_setDescriptionPromise);

    (*m_setDescriptionPromise)->reject(exception);
    m_setDescriptionPromise = Nullopt;
}

static inline bool isRemoteDescriptionTypeValidForState(RTCSdpType type, RTCSignalingState state)
{
    switch (state) {
    case RTCSignalingState::Stable:
        return type == RTCSdpType::Offer;
    case RTCSignalingState::HaveLocalOffer:
        return type == RTCSdpType::Answer || type == RTCSdpType::Pranswer;
    case RTCSignalingState::HaveRemoteOffer:
        return type == RTCSdpType::Offer;
    case RTCSignalingState::HaveRemotePranswer:
        return type == RTCSdpType::Answer || type == RTCSdpType::Pranswer;
    default:
        return false;
    };

    ASSERT_NOT_REACHED();
    return false;
}

void PeerConnectionBackend::setRemoteDescription(RTCSessionDescription& sessionDescription, PeerConnection::VoidPromise promise)
{
    ASSERT(m_peerConnection.signalingState() != RTCSignalingState::Closed);

    if (!isRemoteDescriptionTypeValidForState(sessionDescription.type(), m_peerConnection.signalingState())) {
        promise->reject(INVALID_STATE_ERR, ASCIILiteral("Description type incompatible with current signaling state"));
        return;
    }

    m_setDescriptionPromise = WTFMove(promise);
    doSetRemoteDescription(sessionDescription);
}

void PeerConnectionBackend::setRemoteDescriptionSucceeded()
{
    ASSERT(isMainThread());

    if (m_peerConnection.signalingState() == RTCSignalingState::Closed)
        return;

    ASSERT(m_setDescriptionPromise);

    (*m_setDescriptionPromise)->resolve(nullptr);
    m_setDescriptionPromise = Nullopt;
}

void PeerConnectionBackend::setRemoteDescriptionFailed(const Exception& exception)
{
    ASSERT(isMainThread());

    if (m_peerConnection.signalingState() == RTCSignalingState::Closed)
        return;

    ASSERT(m_setDescriptionPromise);

    (*m_setDescriptionPromise)->reject(exception);
    m_setDescriptionPromise = Nullopt;
}

void PeerConnectionBackend::addIceCandidate(RTCIceCandidate& iceCandidate, PeerConnection::VoidPromise promise)
{
    ASSERT(m_peerConnection.internalSignalingState() != PeerConnectionStates::SignalingState::Closed);

    if (iceCandidate.sdpMid().isNull() && !iceCandidate.sdpMLineIndex()) {
        promise->reject(Exception(TypeError, ASCIILiteral("Trying to add a candidate that is missing both sdpMid and sdpMLineIndex")));
        return;
    }
    m_addIceCandidatePromise = WTFMove(promise);
    doAddIceCandidate(iceCandidate);
}

void PeerConnectionBackend::addIceCandidateSucceeded()
{
    ASSERT(isMainThread());

    if (m_peerConnection.signalingState() == RTCSignalingState::Closed)
        return;

    // FIXME: Update remote description and set ICE connection state to checking if not already done so.
    ASSERT(m_addIceCandidatePromise);

    (*m_addIceCandidatePromise)->resolve(nullptr);
    m_addIceCandidatePromise = Nullopt;
}

void PeerConnectionBackend::addIceCandidateFailed(const Exception& exception)
{
    ASSERT(isMainThread());
    if (m_peerConnection.signalingState() == RTCSignalingState::Closed)
        return;

    ASSERT(m_addIceCandidatePromise);

    (*m_addIceCandidatePromise)->reject(exception);
    m_addIceCandidatePromise = Nullopt;
}

void PeerConnectionBackend::fireICECandidateEvent(PassRefPtr<RTCIceCandidate> candidate)
{
    ASSERT(isMainThread());

    m_peerConnection.fireEvent(RTCPeerConnectionIceEvent::create(false, false, candidate).get());
}

void PeerConnectionBackend::enableICECandidateFiltering()
{
    m_shouldFilterICECandidates = true;
}

void PeerConnectionBackend::disableICECandidateFiltering()
{
    m_shouldFilterICECandidates = false;
    for (auto& pendingICECandidate : m_pendingICECandidates)
        fireICECandidateEvent(RTCIceCandidate::create(WTFMove(pendingICECandidate.sdp), WTFMove(pendingICECandidate.mid), 0));
    m_pendingICECandidates.clear();
}

static inline String filterICECandidate(const String& sdp)
{
    ASSERT(!sdp.contains(" host "));

    if (!sdp.contains(ASCIILiteral(" raddr ")))
        return sdp;

    Vector<String> items;
    sdp.split(' ', items);

    bool skipNextItem = false;
    bool isFirst = true;
    StringBuilder filteredSDP;
    for (auto& item : items) {
        if (skipNextItem) {
            skipNextItem = false;
            continue;
        }
        if (item == "raddr" || item == "rport") {
            skipNextItem = true;
            continue;
        }
        if (isFirst)
            isFirst = false;
        else
            filteredSDP.append(' ');
        filteredSDP.append(item);
    }
    return filteredSDP.toString();
}

void PeerConnectionBackend::newICECandidate(const String& sdp, const String& mid)
{
    if (!m_shouldFilterICECandidates) {
        fireICECandidateEvent(RTCIceCandidate::create(sdp, mid, 0));
        return;
    }
    if (sdp.contains(ASCIILiteral(" host "))) {
        m_pendingICECandidates.append(PendingICECandidate { sdp, mid});
        return;
    }
    fireICECandidateEvent(RTCIceCandidate::create(filterICECandidate(sdp), mid, 0));
}

void PeerConnectionBackend::doneGatheringCandidates()
{
    ASSERT(isMainThread());

    m_peerConnection.fireEvent(RTCPeerConnectionIceEvent::create(false, false, nullptr).get());
    m_peerConnection.updateIceGatheringState(RTCIceGatheringState::Complete);
}

void PeerConnectionBackend::updateSignalingState(RTCSignalingState newSignalingState)
{
    ASSERT(isMainThread());

    if (newSignalingState != m_peerConnection.signalingState()) {
        m_peerConnection.setSignalingState(newSignalingState);
        m_peerConnection.fireEvent(*Event::create(eventNames().signalingstatechangeEvent, false, false));
    }
}

void PeerConnectionBackend::stop()
{
    m_offerAnswerPromise = Nullopt;
    m_setDescriptionPromise = Nullopt;
    m_addIceCandidatePromise = Nullopt;

    doStop();
}

void PeerConnectionBackend::markAsNeedingNegotiation()
{
    if (m_negotiationNeeded)
        return;

    m_negotiationNeeded = true;

    if (m_peerConnection.signalingState() == RTCSignalingState::Stable)
        m_peerConnection.scheduleNegotiationNeededEvent();
}

} // namespace WebCore

#endif // ENABLE(WEB_RTC)
