/** @file JSMOMContentItemCustom.cpp
 *
 * Copyright (C) Espial Limited 2014 - Company confidential - All rights reserved.
 *
 */

#include "config.h"

#if ENABLE(RMAI)
#include "JSMOMChannelListCustom.h"
#include "MOMException.h"

#include "JSMOMContentItem.h"
#include "JSMOMChannelList.h"

extern "C" {
#include "layers.h"
#include "cdf/mom_content_list.h"
}

using namespace JSC;

namespace WebCore {

bool JSMOMChannelList::put(JSC::JSCell* cell, JSC::ExecState* exec, JSC::PropertyName propertyName, JSC::JSValue value, JSC::PutPropertySlot& slot)
{
	return Base::put(cell, exec, propertyName, value, slot);
}

bool JSMOMChannelList::putByIndex(JSC::JSCell* cell, JSC::ExecState* exec, unsigned propertyName, JSC::JSValue value, bool shouldThrow)
{
    if (value.isUndefinedOrNull()) {
        setDOMException(exec, MOMException::INVALID);
        return false;
    }

    JSMOMChannelList* thisObject = jsCast<JSMOMChannelList*>(cell);
    MOMChannelList& imp = static_cast<MOMChannelList&>(thisObject->wrapped());
    mom_content_list list = imp.itemAsContentList();
    mom_content_item item = toMOMContentItem(value)->itemAsItem();
    if (mom_content_item_is_readonly(item))
    {
        setDOMException(exec, MOMException::INVALID);
        return false;
    }

    mom_error err;
    unsigned int length = mom_content_list_length(list);
    if (propertyName >= length)
    {
        /* off the end of the list so extend list by 1 */
        err = mom_content_list_add_item_at( list, item, length );
    }
    else
    {
        err = mom_content_list_replace_item_at( list, item, propertyName );
    }
    ExceptionCode ec;
    MOMException::setFromMOMError(err, ec);
    setDOMException(exec, ec);
    return true;
}

} // namespace WebCore

#endif // ENABLE(RMAI)
