/*
 * Copyright (C) 2010 Google 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.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "SpellChecker.h"

#include "Document.h"
#include "DocumentMarkerController.h"
#include "EditorClient.h"
#include "Frame.h"
#include "HTMLInputElement.h"
#include "HTMLTextAreaElement.h"
#include "Node.h"
#include "Page.h"
#include "PositionIterator.h"
#include "Range.h"
#include "RenderElement.h"
#include "Settings.h"
#include "SimpleRange.h"
#include "TextCheckerClient.h"
#include "TextCheckingHelper.h"
#include "TextIterator.h"
#include "htmlediting.h"

namespace WebCore {

static const int unrequestedSequence = -1;

SpellCheckRequest::SpellCheckRequest(const SimpleRange& checkingRange, const SimpleRange& automaticReplacementRange, const SimpleRange& paragraphRange, const String& text, TextCheckingTypeMask mask, TextCheckingProcessType processType)
    : TextCheckingRequest(unrequestedSequence, text, mask, processType)
    , m_checkingRange(checkingRange)
	, m_automaticReplacementRange(automaticReplacementRange)
    , m_paragraphRange(paragraphRange)
    , m_rootEditableElement(m_checkingRange.start.container->rootEditableElement())
{
}

SpellCheckRequest::~SpellCheckRequest() = default;

// static
RefPtr<SpellCheckRequest> SpellCheckRequest::create(TextCheckingTypeMask textCheckingOptions, TextCheckingProcessType processType, const SimpleRange& checkingRange, const SimpleRange& automaticReplacementRange, const SimpleRange& paragraphRange)
{
    String text = plainText(checkingRange);
    if (text.isEmpty())
        return nullptr;
    return adoptRef(*new SpellCheckRequest(checkingRange, automaticReplacementRange, paragraphRange, text, textCheckingOptions, processType));
}

void SpellCheckRequest::didSucceed(const Vector<TextCheckingResult>& results)
{
    if (!m_checker)
        return;

    Ref<SpellCheckRequest> protectedThis(*this);
    m_checker->didCheckSucceed(m_sequence, results);
    m_checker = nullptr;
}

void SpellCheckRequest::didCancel()
{
    if (!m_checker)
        return;

    Ref<SpellCheckRequest> protectedThis(*this);
    m_checker->didCheckCancel(m_sequence);
    m_checker = nullptr;
}

void SpellCheckRequest::setCheckerAndSequence(SpellChecker* requester, int sequence)
{
    ASSERT(!m_checker);
    ASSERT(m_sequence == unrequestedSequence);
    m_checker = requester;
    m_sequence = sequence;
}

void SpellCheckRequest::requesterDestroyed()
{
    m_checker = 0;
}

SpellChecker::SpellChecker(Document& document)
    : m_document(makeWeakPtr(document))
    , m_lastRequestSequence(0)
    , m_lastProcessedSequence(0)
    , m_timerToProcessQueuedRequest(this, &SpellChecker::timerFiredToProcessQueuedRequest)
{
}

SpellChecker::~SpellChecker()
{
    if (m_processingRequest)
        m_processingRequest->requesterDestroyed();
    for (auto i = m_requestQueue.begin(); i != m_requestQueue.end(); ++i)
        (*i)->requesterDestroyed();
}

TextCheckerClient* SpellChecker::client() const
{
    Page* page = m_document->page();
    if (!page)
        return nullptr;
    return page->editorClient()->textChecker();
}

void SpellChecker::timerFiredToProcessQueuedRequest()
{
    ASSERT(!m_requestQueue.isEmpty());
    if (m_requestQueue.isEmpty())
        return;

    invokeRequest(m_requestQueue.takeFirst());
}

bool SpellChecker::isAsynchronousEnabled() const
{
    return m_document && m_document->settings().asynchronousSpellCheckingEnabled();
}

bool SpellChecker::canCheckAsynchronously(const SimpleRange& range) const
{
    return client() && isCheckable(range) && isAsynchronousEnabled();
}

bool SpellChecker::isCheckable(const SimpleRange& range) const
{
    bool foundRenderer = false;
    auto nodes = intersectingNodes(range);
    for (auto it = nodes.begin(); it != nodes.end(); ++it) {
    	auto& node = *it;
        if (node.renderer()) {
            foundRenderer = true;
            break;
        }
    }
    if (!foundRenderer)
        return false;
    auto& node = range.start.container.get();
    return !isElement(node) || toElement(node).isSpellCheckingEnabled();
}

void SpellChecker::requestCheckingFor(PassRefPtr<SpellCheckRequest> request)
{
    if (!request || !canCheckAsynchronously(request->paragraphRange()))
        return;

    ASSERT(request->sequence() == unrequestedSequence);
    int sequence = ++m_lastRequestSequence;
    if (sequence == unrequestedSequence)
        sequence = ++m_lastRequestSequence;

    request->setCheckerAndSequence(this, sequence);

    if (m_timerToProcessQueuedRequest.isActive() || m_processingRequest) {
        enqueueRequest(request);
        return;
    }

    invokeRequest(request);
}

void SpellChecker::invokeRequest(PassRefPtr<SpellCheckRequest> request)
{
    ASSERT(!m_processingRequest);
    if (!client()) {
        request->didCancel();
        return;
    }

    m_processingRequest = request;
    client()->requestCheckingOfString(m_processingRequest);
}

void SpellChecker::enqueueRequest(PassRefPtr<SpellCheckRequest> request)
{
    ASSERT(request);

    for (auto it = m_requestQueue.begin(); it != m_requestQueue.end(); ++it) {
        if (request->rootEditableElement() != (*it)->rootEditableElement())
            continue;

        *it = request;
        return;
    }

    m_requestQueue.append(request);
}

void SpellChecker::didCheck(int sequence, const Vector<TextCheckingResult>& results)
{
    ASSERT(m_processingRequest);
    ASSERT(m_processingRequest->sequence() == sequence);
    if (m_processingRequest->sequence() != sequence) {
        m_requestQueue.clear();
        return;
    }

#if ENABLE(SPELLING_CHECK)
    m_document->editor().markAndReplaceFor(m_processingRequest, results);
#endif

    if (m_lastProcessedSequence < sequence)
        m_lastProcessedSequence = sequence;

    m_processingRequest.clear();
    if (!m_requestQueue.isEmpty())
        m_timerToProcessQueuedRequest.startOneShot(0);
}

void SpellChecker::didCheckSucceed(int sequence, const Vector<TextCheckingResult>& results)
{
    if (m_processingRequest->sequence() == sequence) {
        unsigned markers = 0;
        if (m_processingRequest->mask() & TextCheckingTypeSpelling)
            markers |= DocumentMarker::Spelling;
        if (m_processingRequest->mask() & TextCheckingTypeGrammar)
            markers |= DocumentMarker::Grammar;
        if (markers)
        	removeMarkers(m_processingRequest->checkingRange(), markers);
    }
    didCheck(sequence, results);
}

void SpellChecker::didCheckCancel(int sequence)
{
    Vector<TextCheckingResult> results;
    didCheck(sequence, results);
}

} // namespace WebCore
