<commit_before>/*
 * WLRemoteObject.j
 * Ratatosk
 *
 * Created by <NAME> on November 16, 2009.
 * Copyright 2009-11, WireLoad Inc. All rights reserved.
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer. 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. Neither the name of WireLoad Inc. 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.
 */

@import "WLRemoteContext.j"
@import "WLRemoteLink.j"

var WLRemoteObjectDirtProof = NO,

    CamelCaseToHyphenPrefixStripper = new RegExp('^[_A-Z]+([A-Z])'),
    CamelCaseToHyphenator = new RegExp("([a-z])([A-Z])");

function CamelCaseToHyphenated(camelCase)
{
    return camelCase.replace(CamelCaseToHyphenPrefixStripper, '$1').replace(CamelCaseToHyphenator, '$1-$2').toLowerCase();
};

/*!
    A WLRemoteObject is a proxy object meant to be synced with a remote object
    through an API and a WLRemoteLink. Every WLRemoteObject must have a
    unique primary key which can be the REST URI of the object (as a
    CPString) or a database numeric id. The exception is for new objects
    have nil as their PK.

    A WLRemoteObject is equal to another WLRemoteObject with the same class
    and key. The object supports loading and saving from and to JSON and
    keeps automatic track of which properties are dirty and need to be saved.

    By default, objects autosave when simple properties are changed.

    Subclasses must implement:
        + (CPArray)remoteProperties

    Subclasses might want to implement:
        - (void)remotePath
*/
@implementation WLRemoteObject : CPObject
{
    id              pk @accessors;

    CPString        _remoteName @accessors(readonly, property=remoteName);
    CPSet           _remoteProperties @accessors(readonly, property=remoteProperties);

    Object          _propertyLastRevision;
    CPSet           _deferredProperties;
    int             _revision;
    int             _lastSyncedRevision;
    CPDate          lastSyncedAt @accessors;
    WLRemoteAction  createAction;
    WLRemoteAction  saveAction;
    WLRemoteAction  deleteAction;
    WLRemoteAction  contentDownloadAction;
    BOOL            _shouldAutoSave @accessors(property=shouldAutoSave);
    BOOL            _shouldAutoLoad @accessors(property=shouldAutoLoad);
    BOOL            _suppressAutoSave;
    BOOL            _suppressRemotePropertiesObservation;
    BOOL            _mustSaveAgain;
    id              _delegate @accessors(property=delegate);

    CPUndoManager   undoManager @accessors;
}

/*!
    Deprectated. Use `[[WLRemoteContext sharedRemoteContext] registeredObjectForRemoteName:[self remoteName] withPk:pk]`.
*/
+ (id)instanceForPk:(id)pk
{
    if (pk === nil || pk === undefined)
        return nil;

    return [[WLRemoteContext sharedRemoteContext] registeredObjectForRemoteName:[self remoteName] withPk:pk];
}

/*!
    Deprectated. Use `[[WLRemoteContext sharedRemoteContext] registeredObjectForRemoteName:[self remoteName] withPk:pk]`.
*/
+ (id)instanceForPk:(id)pk create:(BOOL)shouldCreate
{
    if (pk === nil || pk === undefined)
        return nil;

    var r = [self instanceForPk:pk];

    if (r === nil && shouldCreate)
    {
        var object = [self new];
        // Setting the pk will automatically register it.
        [object setPk:pk];
    }

    return r;
}

/*!
    Deprecated. Use `[[WLRemoteContext sharedRemoteContext] registeredObjectsForRemoteName:[self remoteName]]`.
*/
+ (CPArray)allObjects
{
    return [[WLRemoteContext sharedRemoteContext] registeredObjectsForRemoteName:[self removeNmae]];
}

+ (void)clearInstanceCache
{
    [CPException raise:CPInvalidArgumentException reason:@"Use [WLRemoteContext reset] instead."];
}

+ (void)setDirtProof:(BOOL)aFlag
{
    WLRemoteObjectDirtProof = aFlag;
}

+ (BOOL)isLoadingObjects
{
    // This is not the original purpose, but works out quite nicely.
    return WLRemoteObjectDirtProof;
}

/*!
    The name of the remote resource. The name of the resource combined with the PK of an instance is what uniquely identifies a specific resource. (For many APIs the PK is the resource URI and alone uniquely identifies the resource, but for APIs where the PK is something like an ID number the name is critical so that e.g. User 101 is not considered the same remote object as BlogPost 101.)

    If two classes are alternative implementations for the same remote resource, they should have the same remote name. E.g. if there is a remote resource called a "Shape" and two classes "Circle" and "Rectangle" implement two types of "Shape", their remoteName should be "shape" so that Ratatosk can recognise that both circles and rectangles should go in the same "bucket" of objects.

    By default the remoteName is the class name minus any leading prefix and converted from camelcase to lowercase with dashes. E.g. a remote object class like WLBlogPost would by default have a remoteName of 'blog-post'.
*/
+ (CPString)remoteName
{
    var className = CPStringFromClass([self class]);
    return CamelCaseToHyphenated(className);
}

/*!
    Specify object properties by implementing this class method on subclasses. The format is:

    [
        [<local property name> [, remote property name [, property transformer]]]
    ]

    If no remote property name is specified, the local property name is used as the remote property
    name.

    At a minimum the PK property has to be defined.
*/
+ (CPArray)remoteProperties
{
    return [
        ['pk', 'id']
    ];
}

+ (CPArray)objectsFromJson:jsonArray
{
    var r = [CPArray array];
    for (var i = 0; i < jsonArray.length; i++)
    {
        [r addObject:[[self alloc] initWithJson:jsonArray[i]]];
    }
    return r;
}

/*!
    When shouldAutoLoad is YES and this method returns YES for a property, any remote
    object set to that property will have `ensureLoaded` automatically called.
*/
+ (BOOL)automaticallyLoadsRemoteObjectsForKey:(CPString)aLocalName
{
    var capitalizedName = aLocalName.charAt(0).toUpperCase() + aLocalName.substring(1),
        selector = "automaticallyLoadsRemoteObjectsFor" + capitalizedName;

    if ([[self class] respondsToSelector:selector])
        return objj_msgSend([self class], selector);

    return NO;
}

- (id)init
{
    if (self = [super init])
    {
        _revision = 0;
        _lastSyncedRevision = -1;
        _shouldAutoSave = YES;
        _shouldAutoLoad = YES;
        _remoteName = [[self class] remoteName];
        _remoteProperties = [CPSet set];
        _propertyLastRevision = {};
        _deferredProperties = [CPSet set];
        lastSyncedAt = [CPDate distantPast];

        var remoteProperties = [],
            otherProperties = [[self class] remoteProperties];

        if (otherProperties)
        {
            for (var i = 0, count = [otherProperties count]; i < count; i++)
            {
                var property = otherProperties[i],
                    localName = property[0],
                    remoteName = property[1],
                    transformer = property[2];

                if (!localName)
                    [CPException raise:CPInvalidArgumentException reason:@"Incorrect `+ (CPArray)remoteProperties` for RemoteObject class " + [self class] + "."];
                if (!remoteName)
                    remoteName = localName;
                if (!transformer)
                    transformer = nil;

                [remoteProperties addObject:[RemoteProperty propertyWithLocalName:localName remoteName:remoteName transformer:transformer]];
            }
        }

        [self registerRemoteProperties:remoteProperties];
    }

    return self;
}

- (id)initWithJson:(id)js
{
    _suppressRemotePropertiesObservation = YES;

    if (self = [self init])
    {
        // (This should always be true)
        if (pk === nil || pk  === undefined)
        {
            // Check if the JSON is for an instance we are already tracking.
            var pkProperty = [self pkProperty],
                remotePkName = [pkProperty remoteName];
            if (js[remotePkName] !== undefined)
            {
                var pkValue = js[remotePkName];
                if ([pkProperty valueTransformer])
                    pkValue = [[pkProperty valueTransformer] transformedValue:_value];

                var existingObject = [[self context] registeredObjectForRemoteName:[self remoteName] withPk:pkValue];

                if (existingObject)
                {
                    // Yes we are tracking an existing object. Update that object instead and return it.
                    self = existingObject;
                    [existingObject updateFromJson:js];
                    return self;
                }
            }
        }

        [self updateFromJson:js];
        _suppressRemotePropertiesObservation = NO;
        [self activateRemotePropertiesObservation];
    }

    return self;
}

- (WLRemoteContext)context
{
    // For future compatibility when there can be multiple contexts.
    return [WLRemoteContext sharedRemoteContext];
}

- (void)registerRemoteProperties:(CPArray)someProperties
{
    for (var i = 0, count = [someProperties count]; i < count; i++)
    {
        var property = someProperties[i];
        if ([_remoteProperties containsObject:property])
            continue;

        if (!_suppressRemotePropertiesObservation)
        {
            [self addObserver:self forKeyPath:[property localName] options:nil context:property];
            // FIXME Since the undo manager is no longer read from a central place, this will do nothing.
            // This action needs to be taken when setUndoManager: is received instead.
            [self registerKeyForUndoManagement:[property localName]];
        }
        [_remoteProperties addObject:property];
        [_deferredProperties addObject:property];
    }
}

- (void)registerKeyForUndoManagement:(CPString)aLocalName
{
    if (aLocalName == "pk")
        return;
    [[self undoManager] observeChangesForKeyPath:aLocalName ofObject:self];
}

- (void)pkProperty
{
    return [self remotePropertyForKey:"pk"];
}

- (RemoteProperty)remotePropertyForKey:(CPString)aLocalName
{
    var remotePropertiesEnumerator = [_remoteProperties objectEnumerator],
        property;
    while (property = [remotePropertiesEnumerator nextObject])
        if ([property localName] == aLocalName)
            return property;
    return nil;
}

- (void)activateRemotePropertiesObservation
{
    var remotePropertiesEnumerator = [_remoteProperties objectEnumerator],
        property;
    while (property = [remotePropertiesEnumerator nextObject])
    {
        [self registerKeyForUndoManagement:[property localName]];
        [self addObserver:self forKeyPath:[property localName] options:nil context:property];
    }
}
- (void)_autoLoad:(CPObject)anObject
{
    if ([anObject respondsToSelector:@selector(ensureLoaded)])
        [anObject ensureLoaded];
}

- (void)observeValueForKeyPath:(CPString)aKeyPath ofObject:(id)anObject change:(CPDictionary)change context:(id)aContext
{
    var isBeforeFlag = !![change objectForKey:CPKeyValueChangeNotificationIsPriorKey];
    if (isBeforeFlag)
        return;

    if ([change valueForKey:CPKeyValueChangeKindKey] == CPKeyValueChangeSetting && [_remoteProperties containsObject:aContext])
    {
        var before = [change valueForKey:CPKeyValueChangeOldKey],
            after = [change valueForKey:CPKeyValueChangeNewKey],
            localName = [aContext localName];
        if (before !== after && ((before === nil || after === nil) || (before.isa && ![before isEqual:after])))
            [self makeDirtyProperty:localName];
        [_deferredProperties removeObject:aContext];

        if (_shouldAutoLoad && [[self class] automaticallyLoadsRemoteObjectsForKey:localName])
        {
            if ([after isKindOfClass:[CPArray class]])
                [after makeObjectsPerformSelector:@selector(_autoLoad:) withObject:anObject];
            else
                [self _autoLoad:after];
        }
    }
}

- (void)cleanAll
{
    _propertyLastRevision = {};
}

- (void)cleanProperty:(CPString)localName
{
    delete _propertyLastRevision[localName];
}

- (void)makeAllDirty
{
    var remotePropertiesEnumerator = [_remoteProperties objectEnumerator],
        property;
    while (property = [remotePropertiesEnumerator nextObject])
    {
        [self makeDirtyProperty:[property localName]]
    }
}

- (void)makeDirtyProperty:(CPString)localName
{
    if (WLRemoteObjectDirtProof)
        return;

    _propertyLastRevision[localName] = ++_revision;
    if (!_suppressAutoSave && ![self isNew] && _shouldAutoSave)
    {
        // Run the check for whether we should autosave at the end of the
        // run loop so that batch changes can collate. This also enables
        // the [object setProperty:X];[object cleanAll]; without having to
        // suppress auto saves.
        [[CPRunLoop currentRunLoop] performSelector:"ensureSaved" target:self argument:nil order:0 modes:[CPDefaultRunLoopMode]];
    }
}

/*!
    Mark the named property as not yet having been downloaded so that [instance ensureLoaded] will cause it to be redownloaded.
    You might do this if you know a property has updated server side and needs to be reread.
*/
- (void)invalidateProperty:(CPString)localName
{
    var property = [self remotePropertyForKey:localName];
    if (property == nil)
        [CPException raise:CPInvalidArgumentException reason:@"Unknown property " + localName + "."];

    delete _propertyLastRevision[localName];
    [_deferredProperties addObject:property];
}

- (BOOL)isDirty
{
    return [[self dirtyProperties] count] > 0;
}

- (CPSet)dirtyProperties
{
    var r = [CPSet set],
        property = nil,
        objectEnumerator = [_remoteProperties objectEnumerator];

    while (property = [objectEnumerator nextObject])
    {
        var localName = [property localName];
        if (_propertyLastRevision[localName] && _propertyLastRevision[localName] > _lastSyncedRevision)
            [r addObject:property];
    }
    return r;
}

/*!
    Every property begins 'deferred', meaning unloaded. When a property is set
    through initWithJson, updateFromJson, or a mutator, it is no longer considered
    deferred.
*/
- (BOOL)isPropertyDeferred:(CPString)localName
{
    var property = [self remotePropertyForKey:localName];
    if (!property)
        [CPException raise:CPInvalidArgumentException reason:@"Unknown property " + localName + "."];
    return [_deferredProperties containsObject:property];
}

- (BOOL)isPropertyDirty:(CPString)localName
{
    return _propertyLastRevision[localName] && _propertyLastRevision[localName] > _lastSyncedRevision;
}

- (void)setPk:(id)aPk
{
    if (pk === aPk)
        return;

    var context = [self context];
    [context unregisterObject:self];

    pk = aPk;
    if (pk)
        [context registerObject:self];
}

- (void)updateFromJson:js
{
    var property = nil,
        objectEnumerator = [_remoteProperties objectEnumerator];

    while (property = [objectEnumerator nextObject])
        [self updateFromJson:js remoteProperty:property];
}

- (void)updateFromJson:js preservingDirtyProperties:(BOOL)shouldPreserveDirty
{
    var property = nil,
        objectEnumerator = [_remoteProperties objectEnumerator];

    while (property = [objectEnumerator nextObject])
    {
        // If the local version is changed, don't overwrite it with the remote.
        if (shouldPreserveDirty && [[self dirtyProperties] containsObject:property])
            continue;
        [self updateFromJson:js remoteProperty:property];
    }
}

- (void)updateFromJson:js remoteProperty:(RemoteProperty)aProperty
{
    var remoteName = [aProperty remoteName];
    if (js[remoteName] !== undefined)
    {
        var after = js[remoteName],
            localName = [aProperty localName];
        if ([aProperty valueTransformer])
            after = [[aProperty valueTransformer] transformedValue:after];

        var before = [self valueForKey:localName];
        // Avoid calling setValue:forKey: if we just received the value we already have. This will
        // happen frequently if `PUT` / `PATCH` requests respond with the object representation - most fields
        // will be unchanged and we don't want expensive KVO notifications to go out needlessly.
        if (before !== after && ((before === nil && after !== nil) || ![before isEqual:after]))
        {
            // CPLog.debug("Updating property %@ from JSON (before: %@ after: %@)", localName, before, after);
            [self setValue:after forKey:localName];
        }

        [_deferredProperties removeObject:aProperty];
    }
}

- (id)asJSObjectForProperties:(CPSet)someProperties
{
    var r = {};

    [someProperties enumerateObjectsUsingBlock:function(aProperty)
        {
            var aValue = [self valueForKey:[aProperty localName]],
                aValueTransformer = [aProperty valueTransformer];
            if (aValueTransformer && [[aValueTransformer class] allowsReverseTransformation])
                aValue = [aValueTransformer reverseTransformedValue:aValue];
            r[[aProperty remoteName]] = aValue;
        }
    ];

    return r;
}

- (id)asPatchJSObject
{
    return [self asJSObjectForProperties:[self dirtyProperties]];
}

- (id)asJSObject
{
    return [self asJSObjectForProperties:[self remoteProperties]];
}

- (BOOL)isEqual:(id)anObject
{
    if (self === anObject)
        return YES;

    if (![anObject isKindOfClass:WLRemoteObject])
        return NO;

    if (![[anObject remoteName] isEqual:[self remoteName]])
        return NO;

    // Entries with no primary key can only be equal if they
    // are identical.
    if ([self pk] === nil)
        return NO;

    return [self pk] == [anObject pk];
}

/*!
    The path of this resource within the API. The path should not include the path to the API root (see WLRemoteLink).

    By default, the PK is assumed to be the canonical resource URI.
*/
- (CPString)remotePath
{
    return [self pk];
}

/*!
    The path to use when GETing (downloading) this resource. By default this is [self remotePath].
*/
- (CPString)getPath
{
    return [self remotePath];
}

/*!
    The path to use when POSTing (creating) a new resource. By default this is [self remotePath].
*/
- (CPString)postPath
{
    return [self remotePath];
}

/*!
    The path to use when PUTting (updating) this resource. By default this is [self remotePath].
*/
- (CPString)putPath
{
    return [self remotePath];
}

/*!
    The path to use when PATCHing (updating) this resource. By default this is [self remotePath].
*/
- (CPString)patchPath
{
    return [self remotePath];
}

/*!
    The path to use when DELETEing this resource. By default this is [self remotePath].
*/
- (CPString)deletePath
{
    return [self remotePath];
}

- (BOOL)isNew
{
    return pk === nil || pk === undefined;
}

/*!
    Create or recreate this object remotely.
*/
- (void)create
{
    [[self undoManager] registerUndoWithTarget:self
                                      selector:@selector(delete)
                                        object:nil];

    [self ensureCreated];
}

/*!
    Delete this object remotely.
*/
- (void)delete
{
    [[self undoManager] registerUndoWithTarget:self
                               selector:@selector(create)
                                 object:nil];

    [self ensureDeleted];
}

- (void)ensureCreated
{
    if (![self isNew] || createAction !== nil)
        return;

    // FIXME Should this be here or in init somewhere? In init we don't yet know if
    // this object will be loaded from remote or if it's being created.

    // Since we're creating the object, there are no deferred fields. Without clearing
    // these, ensureLoaded would lead to a pointless GET.
    _deferredProperties = [CPSet set];

    // Also consider all fields dirty so that any initial values get POSTed. E.g. if a new
    // RemoteObject has a title attribute like 'unnamed' by default, that should be transmitted
    // to the server.
    [self makeAllDirty];

    createAction = [WLRemoteAction schedule:WLRemoteActionPostType path:[self postPath] delegate:self message:"Create " + [self description]];
}

- (void)ensureDeleted
{
    if ([self isNew] || deleteAction !== nil)
        return;

    // Path might not be known yet. A delete can be scheduled before the object has been created. The path will be
    // set in remoteActionWillBegin when the path must be known.
    deleteAction = [WLRemoteAction schedule:WLRemoteActionDeleteType path:nil delegate:self message:"Delete " + [self description]];
}

- (void)ensureLoaded
{
    if ([self isNew] || [_deferredProperties count] == 0 || contentDownloadAction !== nil)
        return;

    [self reload];
}

/*!
    Reload the properties of this resource from the server. Also see `ensureLoaded` which only causes the resource to
    be retrieved if it hasn't already been fully downloaded.
*/
- (void)reload
{
    // One download is enough.
    if (contentDownloadAction && ![contentDownloadAction isStarted])
        return;

    // Path might not be known yet. A load can be scheduled before the object has been created. The path will be
    // set in remoteActionWillBegin when the path must be known.
    contentDownloadAction = [WLRemoteAction schedule:WLRemoteActionGetType path:nil delegate:self message:"Loading " + [self description]];
}

- (void)ensureSaved
{
    if (![self isDirty])
        return;

    // If a save action is already in the pipe, relax. Same if the object is about to be created - we'll transfer up to date
    // information once the creation action fires.
    if (createAction !== nil || saveAction !== nil)
    {
        if (![createAction isStarted] && ![saveAction isStarted])
            return;

        /*
            The ongoing save is saving stale information. We must ensure
            another save will be scheduled after this one.
        */
        _mustSaveAgain = YES;
        return;
    }

    var dirtDescription = [[[[self dirtyProperties] valueForKeyPath:@"localName"] allObjects] componentsJoinedByString:@", "];

    CPLog.info("Save " + [self description] + " dirt: " + dirtDescription);

    saveAction = [WLRemoteAction schedule:[[[self context] remoteLink] saveActionType] path:nil delegate:self message:"Save " + [self description]];
}

- (void)remoteActionWillBegin:(WLRemoteAction)anAction
{
    if (anAction === createAction)
    {
        if (pk)
        {
            CPLog.error("Attempt to create an existing object");
            return;
        }

        [anAction setPayload:[self asJSObject]];
        // Assume the action will succeed or retry until it does.
        [self setLastSyncedAt:[CPDate date]];
        _lastSyncedRevision = _revision;
    }
    else if (anAction === deleteAction)
    {
        if (pk === nil)
        {
            CPLog.error("Attempt to delete a non existant object");
            return;
        }

        [anAction setPayload:nil];
        // Assume the action will succeed or retry until it does.
        [self setLastSyncedAt:[CPDate date]];
        _lastSyncedRevision = _revision;
        [anAction setPath:[self deletePath]];
    }
    else if (anAction === saveAction)
    {
        if (!pk)
        {
            CPLog.error("Attempt to save non created object " + [self description]);
            return;
        }

        var patchAction = [anAction type] === WLRemoteActionPatchType;

        [anAction setMessage:"Saving " + [self description]];
        [anAction setPayload:patchAction ? [self asPatchJSObject] : [self asJSObject]];
        [anAction setPath:patchAction ? [self patchPath] : [self putPath]];

        // Assume the action will succeed or retry until it does.
        [self setLastSyncedAt:[CPDate date]];
        _lastSyncedRevision = _revision;
    }
    else if (anAction === contentDownloadAction)
    {
        [anAction setPath:[self getPath]];
    }
}

- (void)remoteActionDidReceiveResourceRepresentation:(Object)aResult
{
    [WLRemoteObject setDirtProof:YES];
    [[self undoManager] disableUndoRegistration];
    // Take any data received from the POST/PUT/PATCH and update the object correspondingly -
    // in particular we might need any primary key that was generated. We could also get new
    // data for updated_at style fields.

    // At the same time we don't want to overwrite any changes the user made while the request
    // was processing, so we preserve dirty properties here.
    [self updateFromJson:aResult preservingDirtyProperties:YES];
    [[self undoManager] enableUndoRegistration];
    [WLRemoteObject setDirtProof:NO];
}

- (void)remoteActionDidFinish:(WLRemoteAction)anAction
{
    if (anAction === createAction)
    {
        [self remoteActionDidReceiveResourceRepresentation:[anAction result]];

        createAction = nil;
        if ([_delegate respondsToSelector:@selector(remoteObjectWasCreated:)])
            [_delegate remoteObjectWasCreated:self];
    }
    else if (anAction === deleteAction)
    {
        // The previous PK is now gone.
        [self setPk:nil];

        // There is nothing to save anymore.
        [saveAction cancel];
        saveAction = nil;

        // After the object has been deleted, the next call to 'ensureCreated' will
        // create a new object. When that creation happens all the data should be
        // considered dirty to ensure it gets sent with the creation.
        [self makeAllDirty];

        deleteAction = nil;
        [self remoteObjectWasDeleted];
    }
    else if (anAction === saveAction)
    {
        if ([anAction result])
            [self remoteActionDidReceiveResourceRepresentation:[anAction result]];

        saveAction = nil;
        if (_mustSaveAgain)
        {
            _mustSaveAgain = NO;
            [self ensureSaved];
        }
    }
    else if (anAction === contentDownloadAction)
    {
        // Assume whatever was downloaded is the most current info, so nothing gets dirty.
        [WLRemoteObject setDirtProof:YES];
        [[self undoManager] disableUndoRegistration];
        [self updateFromJson:[anAction result]];
        [[self undoManager] enableUndoRegistration];
        [WLRemoteObject setDirtProof:NO];

        contentDownloadAction = nil;
        [self remoteObjectWasLoaded];
    }
}

- (void)remoteObjectWasLoaded
{
    if ([_delegate respondsToSelector:@selector(remoteObjectWasLoaded:)])
        [_delegate remoteObjectWasLoaded:self];
}

- (void)remoteObjectWasDeleted
{
    if ([_delegate respondsToSelector:@selector(remoteObjectWasDeleted:)])
        [_delegate remoteObjectWasDeleted:self];
}

#pragma mark CPObject

- (CPString)description
{
    return "<" + [self class] + " " + [self UID] + (pk ? " " + pk : "") + ">";
}

@end

var WLRemoteObjectClassKey = "WLRemoteObjectClassKey",
    WLRemoteObjectPkKey = "WLRemoteObjectPkKey";

@implementation WLRemoteObject (CPCoding)

- (id)initWithCoder:(CPCoder)aCoder
{
    if (self = [self init])
    {
        pk = [aCoder decodeObjectForKey:@"$pk"];

        if (pk)
        {
            var existingObject = [[self class] instanceForPk:pk];
            if (existingObject)
                return existingObject;
        }

        [_remoteProperties enumerateObjectsUsingBlock:function(aProperty, idx)
            {
                [self setValue:[aCoder decodeObjectForKey:"$" + [aProperty localName]] forKey:[aProperty localName]];
            }];
    }

    return self;
}

- (void)encodeWithCoder:(CPCoder)aCoder
{
    [_remoteProperties enumerateObjectsUsingBlock:function(aProperty, idx)
        {
            [aCoder encodeObject:[self valueForKey:[aProperty localName]] forKey:"$" + [aProperty localName]];
        }];
}

@end

@implementation RemoteProperty : CPObject
{
    CPString            localName @accessors;
    CPString            remoteName @accessors;
    CPValueTransformer  valueTransformer @accessors;
}

+ (id)propertyWithName:(CPString)aName
{
    return [self propertyWithLocalName:aName remoteName:aName transformer:nil];
}

+ (id)propertyWithLocalName:(CPString)aLocalName remoteName:(CPString)aRemoteName
{
    return [self propertyWithLocalName:aLocalName remoteName:aRemoteName transformer:nil];
}

+ (id)propertyWithLocalName:(CPString)aLocalName remoteName:(CPString)aRemoteName transformer:(CPValueTransformer)aTransformer
{
    var r = [RemoteProperty new];
    [r setLocalName:aLocalName];
    [r setRemoteName:aRemoteName];
    [r setValueTransformer:aTransformer];
    return r;
}

- (BOOL)isEqual:(id)anOther
{
    return (anOther !== nil && anOther.isa && [anOther isKindOfClass:RemoteProperty] && anOther.localName == self.localName);
}

- (CPString)description
{
    return "<RemoteProperty " + remoteName + ":" + localName + ">";
}

@end

<commit_msg>Fixed typo<commit_after>/*
 * WLRemoteObject.j
 * Ratatosk
 *
 * Created by <NAME> on November 16, 2009.
 * Copyright 2009-11, WireLoad Inc. All rights reserved.
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer. 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. Neither the name of WireLoad Inc. 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.
 */

@import "WLRemoteContext.j"
@import "WLRemoteLink.j"

var WLRemoteObjectDirtProof = NO,

    CamelCaseToHyphenPrefixStripper = new RegExp('^[_A-Z]+([A-Z])'),
    CamelCaseToHyphenator = new RegExp("([a-z])([A-Z])");

function CamelCaseToHyphenated(camelCase)
{
    return camelCase.replace(CamelCaseToHyphenPrefixStripper, '$1').replace(CamelCaseToHyphenator, '$1-$2').toLowerCase();
};

/*!
    A WLRemoteObject is a proxy object meant to be synced with a remote object
    through an API and a WLRemoteLink. Every WLRemoteObject must have a
    unique primary key which can be the REST URI of the object (as a
    CPString) or a database numeric id. The exception is for new objects
    have nil as their PK.

    A WLRemoteObject is equal to another WLRemoteObject with the same class
    and key. The object supports loading and saving from and to JSON and
    keeps automatic track of which properties are dirty and need to be saved.

    By default, objects autosave when simple properties are changed.

    Subclasses must implement:
        + (CPArray)remoteProperties

    Subclasses might want to implement:
        - (void)remotePath
*/
@implementation WLRemoteObject : CPObject
{
    id              pk @accessors;

    CPString        _remoteName @accessors(readonly, property=remoteName);
    CPSet           _remoteProperties @accessors(readonly, property=remoteProperties);

    Object          _propertyLastRevision;
    CPSet           _deferredProperties;
    int             _revision;
    int             _lastSyncedRevision;
    CPDate          lastSyncedAt @accessors;
    WLRemoteAction  createAction;
    WLRemoteAction  saveAction;
    WLRemoteAction  deleteAction;
    WLRemoteAction  contentDownloadAction;
    BOOL            _shouldAutoSave @accessors(property=shouldAutoSave);
    BOOL            _shouldAutoLoad @accessors(property=shouldAutoLoad);
    BOOL            _suppressAutoSave;
    BOOL            _suppressRemotePropertiesObservation;
    BOOL            _mustSaveAgain;
    id              _delegate @accessors(property=delegate);

    CPUndoManager   undoManager @accessors;
}

/*!
    Deprectated. Use `[[WLRemoteContext sharedRemoteContext] registeredObjectForRemoteName:[self remoteName] withPk:pk]`.
*/
+ (id)instanceForPk:(id)pk
{
    if (pk === nil || pk === undefined)
        return nil;

    return [[WLRemoteContext sharedRemoteContext] registeredObjectForRemoteName:[self remoteName] withPk:pk];
}

/*!
    Deprectated. Use `[[WLRemoteContext sharedRemoteContext] registeredObjectForRemoteName:[self remoteName] withPk:pk]`.
*/
+ (id)instanceForPk:(id)pk create:(BOOL)shouldCreate
{
    if (pk === nil || pk === undefined)
        return nil;

    var r = [self instanceForPk:pk];

    if (r === nil && shouldCreate)
    {
        var object = [self new];
        // Setting the pk will automatically register it.
        [object setPk:pk];
    }

    return r;
}

/*!
    Deprecated. Use `[[WLRemoteContext sharedRemoteContext] registeredObjectsForRemoteName:[self remoteName]]`.
*/
+ (CPArray)allObjects
{
    return [[WLRemoteContext sharedRemoteContext] registeredObjectsForRemoteName:[self remoteName]];
}

+ (void)clearInstanceCache
{
    [CPException raise:CPInvalidArgumentException reason:@"Use [WLRemoteContext reset] instead."];
}

+ (void)setDirtProof:(BOOL)aFlag
{
    WLRemoteObjectDirtProof = aFlag;
}

+ (BOOL)isLoadingObjects
{
    // This is not the original purpose, but works out quite nicely.
    return WLRemoteObjectDirtProof;
}

/*!
    The name of the remote resource. The name of the resource combined with the PK of an instance is what uniquely identifies a specific resource. (For many APIs the PK is the resource URI and alone uniquely identifies the resource, but for APIs where the PK is something like an ID number the name is critical so that e.g. User 101 is not considered the same remote object as BlogPost 101.)

    If two classes are alternative implementations for the same remote resource, they should have the same remote name. E.g. if there is a remote resource called a "Shape" and two classes "Circle" and "Rectangle" implement two types of "Shape", their remoteName should be "shape" so that Ratatosk can recognise that both circles and rectangles should go in the same "bucket" of objects.

    By default the remoteName is the class name minus any leading prefix and converted from camelcase to lowercase with dashes. E.g. a remote object class like WLBlogPost would by default have a remoteName of 'blog-post'.
*/
+ (CPString)remoteName
{
    var className = CPStringFromClass([self class]);
    return CamelCaseToHyphenated(className);
}

/*!
    Specify object properties by implementing this class method on subclasses. The format is:

    [
        [<local property name> [, remote property name [, property transformer]]]
    ]

    If no remote property name is specified, the local property name is used as the remote property
    name.

    At a minimum the PK property has to be defined.
*/
+ (CPArray)remoteProperties
{
    return [
        ['pk', 'id']
    ];
}

+ (CPArray)objectsFromJson:jsonArray
{
    var r = [CPArray array];
    for (var i = 0; i < jsonArray.length; i++)
    {
        [r addObject:[[self alloc] initWithJson:jsonArray[i]]];
    }
    return r;
}

/*!
    When shouldAutoLoad is YES and this method returns YES for a property, any remote
    object set to that property will have `ensureLoaded` automatically called.
*/
+ (BOOL)automaticallyLoadsRemoteObjectsForKey:(CPString)aLocalName
{
    var capitalizedName = aLocalName.charAt(0).toUpperCase() + aLocalName.substring(1),
        selector = "automaticallyLoadsRemoteObjectsFor" + capitalizedName;

    if ([[self class] respondsToSelector:selector])
        return objj_msgSend([self class], selector);

    return NO;
}

- (id)init
{
    if (self = [super init])
    {
        _revision = 0;
        _lastSyncedRevision = -1;
        _shouldAutoSave = YES;
        _shouldAutoLoad = YES;
        _remoteName = [[self class] remoteName];
        _remoteProperties = [CPSet set];
        _propertyLastRevision = {};
        _deferredProperties = [CPSet set];
        lastSyncedAt = [CPDate distantPast];

        var remoteProperties = [],
            otherProperties = [[self class] remoteProperties];

        if (otherProperties)
        {
            for (var i = 0, count = [otherProperties count]; i < count; i++)
            {
                var property = otherProperties[i],
                    localName = property[0],
                    remoteName = property[1],
                    transformer = property[2];

                if (!localName)
                    [CPException raise:CPInvalidArgumentException reason:@"Incorrect `+ (CPArray)remoteProperties` for RemoteObject class " + [self class] + "."];
                if (!remoteName)
                    remoteName = localName;
                if (!transformer)
                    transformer = nil;

                [remoteProperties addObject:[RemoteProperty propertyWithLocalName:localName remoteName:remoteName transformer:transformer]];
            }
        }

        [self registerRemoteProperties:remoteProperties];
    }

    return self;
}

- (id)initWithJson:(id)js
{
    _suppressRemotePropertiesObservation = YES;

    if (self = [self init])
    {
        // (This should always be true)
        if (pk === nil || pk  === undefined)
        {
            // Check if the JSON is for an instance we are already tracking.
            var pkProperty = [self pkProperty],
                remotePkName = [pkProperty remoteName];
            if (js[remotePkName] !== undefined)
            {
                var pkValue = js[remotePkName];
                if ([pkProperty valueTransformer])
                    pkValue = [[pkProperty valueTransformer] transformedValue:_value];

                var existingObject = [[self context] registeredObjectForRemoteName:[self remoteName] withPk:pkValue];

                if (existingObject)
                {
                    // Yes we are tracking an existing object. Update that object instead and return it.
                    self = existingObject;
                    [existingObject updateFromJson:js];
                    return self;
                }
            }
        }

        [self updateFromJson:js];
        _suppressRemotePropertiesObservation = NO;
        [self activateRemotePropertiesObservation];
    }

    return self;
}

- (WLRemoteContext)context
{
    // For future compatibility when there can be multiple contexts.
    return [WLRemoteContext sharedRemoteContext];
}

- (void)registerRemoteProperties:(CPArray)someProperties
{
    for (var i = 0, count = [someProperties count]; i < count; i++)
    {
        var property = someProperties[i];
        if ([_remoteProperties containsObject:property])
            continue;

        if (!_suppressRemotePropertiesObservation)
        {
            [self addObserver:self forKeyPath:[property localName] options:nil context:property];
            // FIXME Since the undo manager is no longer read from a central place, this will do nothing.
            // This action needs to be taken when setUndoManager: is received instead.
            [self registerKeyForUndoManagement:[property localName]];
        }
        [_remoteProperties addObject:property];
        [_deferredProperties addObject:property];
    }
}

- (void)registerKeyForUndoManagement:(CPString)aLocalName
{
    if (aLocalName == "pk")
        return;
    [[self undoManager] observeChangesForKeyPath:aLocalName ofObject:self];
}

- (void)pkProperty
{
    return [self remotePropertyForKey:"pk"];
}

- (RemoteProperty)remotePropertyForKey:(CPString)aLocalName
{
    var remotePropertiesEnumerator = [_remoteProperties objectEnumerator],
        property;
    while (property = [remotePropertiesEnumerator nextObject])
        if ([property localName] == aLocalName)
            return property;
    return nil;
}

- (void)activateRemotePropertiesObservation
{
    var remotePropertiesEnumerator = [_remoteProperties objectEnumerator],
        property;
    while (property = [remotePropertiesEnumerator nextObject])
    {
        [self registerKeyForUndoManagement:[property localName]];
        [self addObserver:self forKeyPath:[property localName] options:nil context:property];
    }
}
- (void)_autoLoad:(CPObject)anObject
{
    if ([anObject respondsToSelector:@selector(ensureLoaded)])
        [anObject ensureLoaded];
}

- (void)observeValueForKeyPath:(CPString)aKeyPath ofObject:(id)anObject change:(CPDictionary)change context:(id)aContext
{
    var isBeforeFlag = !![change objectForKey:CPKeyValueChangeNotificationIsPriorKey];
    if (isBeforeFlag)
        return;

    if ([change valueForKey:CPKeyValueChangeKindKey] == CPKeyValueChangeSetting && [_remoteProperties containsObject:aContext])
    {
        var before = [change valueForKey:CPKeyValueChangeOldKey],
            after = [change valueForKey:CPKeyValueChangeNewKey],
            localName = [aContext localName];
        if (before !== after && ((before === nil || after === nil) || (before.isa && ![before isEqual:after])))
            [self makeDirtyProperty:localName];
        [_deferredProperties removeObject:aContext];

        if (_shouldAutoLoad && [[self class] automaticallyLoadsRemoteObjectsForKey:localName])
        {
            if ([after isKindOfClass:[CPArray class]])
                [after makeObjectsPerformSelector:@selector(_autoLoad:) withObject:anObject];
            else
                [self _autoLoad:after];
        }
    }
}

- (void)cleanAll
{
    _propertyLastRevision = {};
}

- (void)cleanProperty:(CPString)localName
{
    delete _propertyLastRevision[localName];
}

- (void)makeAllDirty
{
    var remotePropertiesEnumerator = [_remoteProperties objectEnumerator],
        property;
    while (property = [remotePropertiesEnumerator nextObject])
    {
        [self makeDirtyProperty:[property localName]]
    }
}

- (void)makeDirtyProperty:(CPString)localName
{
    if (WLRemoteObjectDirtProof)
        return;

    _propertyLastRevision[localName] = ++_revision;
    if (!_suppressAutoSave && ![self isNew] && _shouldAutoSave)
    {
        // Run the check for whether we should autosave at the end of the
        // run loop so that batch changes can collate. This also enables
        // the [object setProperty:X];[object cleanAll]; without having to
        // suppress auto saves.
        [[CPRunLoop currentRunLoop] performSelector:"ensureSaved" target:self argument:nil order:0 modes:[CPDefaultRunLoopMode]];
    }
}

/*!
    Mark the named property as not yet having been downloaded so that [instance ensureLoaded] will cause it to be redownloaded.
    You might do this if you know a property has updated server side and needs to be reread.
*/
- (void)invalidateProperty:(CPString)localName
{
    var property = [self remotePropertyForKey:localName];
    if (property == nil)
        [CPException raise:CPInvalidArgumentException reason:@"Unknown property " + localName + "."];

    delete _propertyLastRevision[localName];
    [_deferredProperties addObject:property];
}

- (BOOL)isDirty
{
    return [[self dirtyProperties] count] > 0;
}

- (CPSet)dirtyProperties
{
    var r = [CPSet set],
        property = nil,
        objectEnumerator = [_remoteProperties objectEnumerator];

    while (property = [objectEnumerator nextObject])
    {
        var localName = [property localName];
        if (_propertyLastRevision[localName] && _propertyLastRevision[localName] > _lastSyncedRevision)
            [r addObject:property];
    }
    return r;
}

/*!
    Every property begins 'deferred', meaning unloaded. When a property is set
    through initWithJson, updateFromJson, or a mutator, it is no longer considered
    deferred.
*/
- (BOOL)isPropertyDeferred:(CPString)localName
{
    var property = [self remotePropertyForKey:localName];
    if (!property)
        [CPException raise:CPInvalidArgumentException reason:@"Unknown property " + localName + "."];
    return [_deferredProperties containsObject:property];
}

- (BOOL)isPropertyDirty:(CPString)localName
{
    return _propertyLastRevision[localName] && _propertyLastRevision[localName] > _lastSyncedRevision;
}

- (void)setPk:(id)aPk
{
    if (pk === aPk)
        return;

    var context = [self context];
    [context unregisterObject:self];

    pk = aPk;
    if (pk)
        [context registerObject:self];
}

- (void)updateFromJson:js
{
    var property = nil,
        objectEnumerator = [_remoteProperties objectEnumerator];

    while (property = [objectEnumerator nextObject])
        [self updateFromJson:js remoteProperty:property];
}

- (void)updateFromJson:js preservingDirtyProperties:(BOOL)shouldPreserveDirty
{
    var property = nil,
        objectEnumerator = [_remoteProperties objectEnumerator];

    while (property = [objectEnumerator nextObject])
    {
        // If the local version is changed, don't overwrite it with the remote.
        if (shouldPreserveDirty && [[self dirtyProperties] containsObject:property])
            continue;
        [self updateFromJson:js remoteProperty:property];
    }
}

- (void)updateFromJson:js remoteProperty:(RemoteProperty)aProperty
{
    var remoteName = [aProperty remoteName];
    if (js[remoteName] !== undefined)
    {
        var after = js[remoteName],
            localName = [aProperty localName];
        if ([aProperty valueTransformer])
            after = [[aProperty valueTransformer] transformedValue:after];

        var before = [self valueForKey:localName];
        // Avoid calling setValue:forKey: if we just received the value we already have. This will
        // happen frequently if `PUT` / `PATCH` requests respond with the object representation - most fields
        // will be unchanged and we don't want expensive KVO notifications to go out needlessly.
        if (before !== after && ((before === nil && after !== nil) || ![before isEqual:after]))
        {
            // CPLog.debug("Updating property %@ from JSON (before: %@ after: %@)", localName, before, after);
            [self setValue:after forKey:localName];
        }

        [_deferredProperties removeObject:aProperty];
    }
}

- (id)asJSObjectForProperties:(CPSet)someProperties
{
    var r = {};

    [someProperties enumerateObjectsUsingBlock:function(aProperty)
        {
            var aValue = [self valueForKey:[aProperty localName]],
                aValueTransformer = [aProperty valueTransformer];
            if (aValueTransformer && [[aValueTransformer class] allowsReverseTransformation])
                aValue = [aValueTransformer reverseTransformedValue:aValue];
            r[[aProperty remoteName]] = aValue;
        }
    ];

    return r;
}

- (id)asPatchJSObject
{
    return [self asJSObjectForProperties:[self dirtyProperties]];
}

- (id)asJSObject
{
    return [self asJSObjectForProperties:[self remoteProperties]];
}

- (BOOL)isEqual:(id)anObject
{
    if (self === anObject)
        return YES;

    if (![anObject isKindOfClass:WLRemoteObject])
        return NO;

    if (![[anObject remoteName] isEqual:[self remoteName]])
        return NO;

    // Entries with no primary key can only be equal if they
    // are identical.
    if ([self pk] === nil)
        return NO;

    return [self pk] == [anObject pk];
}

/*!
    The path of this resource within the API. The path should not include the path to the API root (see WLRemoteLink).

    By default, the PK is assumed to be the canonical resource URI.
*/
- (CPString)remotePath
{
    return [self pk];
}

/*!
    The path to use when GETing (downloading) this resource. By default this is [self remotePath].
*/
- (CPString)getPath
{
    return [self remotePath];
}

/*!
    The path to use when POSTing (creating) a new resource. By default this is [self remotePath].
*/
- (CPString)postPath
{
    return [self remotePath];
}

/*!
    The path to use when PUTting (updating) this resource. By default this is [self remotePath].
*/
- (CPString)putPath
{
    return [self remotePath];
}

/*!
    The path to use when PATCHing (updating) this resource. By default this is [self remotePath].
*/
- (CPString)patchPath
{
    return [self remotePath];
}

/*!
    The path to use when DELETEing this resource. By default this is [self remotePath].
*/
- (CPString)deletePath
{
    return [self remotePath];
}

- (BOOL)isNew
{
    return pk === nil || pk === undefined;
}

/*!
    Create or recreate this object remotely.
*/
- (void)create
{
    [[self undoManager] registerUndoWithTarget:self
                                      selector:@selector(delete)
                                        object:nil];

    [self ensureCreated];
}

/*!
    Delete this object remotely.
*/
- (void)delete
{
    [[self undoManager] registerUndoWithTarget:self
                               selector:@selector(create)
                                 object:nil];

    [self ensureDeleted];
}

- (void)ensureCreated
{
    if (![self isNew] || createAction !== nil)
        return;

    // FIXME Should this be here or in init somewhere? In init we don't yet know if
    // this object will be loaded from remote or if it's being created.

    // Since we're creating the object, there are no deferred fields. Without clearing
    // these, ensureLoaded would lead to a pointless GET.
    _deferredProperties = [CPSet set];

    // Also consider all fields dirty so that any initial values get POSTed. E.g. if a new
    // RemoteObject has a title attribute like 'unnamed' by default, that should be transmitted
    // to the server.
    [self makeAllDirty];

    createAction = [WLRemoteAction schedule:WLRemoteActionPostType path:[self postPath] delegate:self message:"Create " + [self description]];
}

- (void)ensureDeleted
{
    if ([self isNew] || deleteAction !== nil)
        return;

    // Path might not be known yet. A delete can be scheduled before the object has been created. The path will be
    // set in remoteActionWillBegin when the path must be known.
    deleteAction = [WLRemoteAction schedule:WLRemoteActionDeleteType path:nil delegate:self message:"Delete " + [self description]];
}

- (void)ensureLoaded
{
    if ([self isNew] || [_deferredProperties count] == 0 || contentDownloadAction !== nil)
        return;

    [self reload];
}

/*!
    Reload the properties of this resource from the server. Also see `ensureLoaded` which only causes the resource to
    be retrieved if it hasn't already been fully downloaded.
*/
- (void)reload
{
    // One download is enough.
    if (contentDownloadAction && ![contentDownloadAction isStarted])
        return;

    // Path might not be known yet. A load can be scheduled before the object has been created. The path will be
    // set in remoteActionWillBegin when the path must be known.
    contentDownloadAction = [WLRemoteAction schedule:WLRemoteActionGetType path:nil delegate:self message:"Loading " + [self description]];
}

- (void)ensureSaved
{
    if (![self isDirty])
        return;

    // If a save action is already in the pipe, relax. Same if the object is about to be created - we'll transfer up to date
    // information once the creation action fires.
    if (createAction !== nil || saveAction !== nil)
    {
        if (![createAction isStarted] && ![saveAction isStarted])
            return;

        /*
            The ongoing save is saving stale information. We must ensure
            another save will be scheduled after this one.
        */
        _mustSaveAgain = YES;
        return;
    }

    var dirtDescription = [[[[self dirtyProperties] valueForKeyPath:@"localName"] allObjects] componentsJoinedByString:@", "];

    CPLog.info("Save " + [self description] + " dirt: " + dirtDescription);

    saveAction = [WLRemoteAction schedule:[[[self context] remoteLink] saveActionType] path:nil delegate:self message:"Save " + [self description]];
}

- (void)remoteActionWillBegin:(WLRemoteAction)anAction
{
    if (anAction === createAction)
    {
        if (pk)
        {
            CPLog.error("Attempt to create an existing object");
            return;
        }

        [anAction setPayload:[self asJSObject]];
        // Assume the action will succeed or retry until it does.
        [self setLastSyncedAt:[CPDate date]];
        _lastSyncedRevision = _revision;
    }
    else if (anAction === deleteAction)
    {
        if (pk === nil)
        {
            CPLog.error("Attempt to delete a non existant object");
            return;
        }

        [anAction setPayload:nil];
        // Assume the action will succeed or retry until it does.
        [self setLastSyncedAt:[CPDate date]];
        _lastSyncedRevision = _revision;
        [anAction setPath:[self deletePath]];
    }
    else if (anAction === saveAction)
    {
        if (!pk)
        {
            CPLog.error("Attempt to save non created object " + [self description]);
            return;
        }

        var patchAction = [anAction type] === WLRemoteActionPatchType;

        [anAction setMessage:"Saving " + [self description]];
        [anAction setPayload:patchAction ? [self asPatchJSObject] : [self asJSObject]];
        [anAction setPath:patchAction ? [self patchPath] : [self putPath]];

        // Assume the action will succeed or retry until it does.
        [self setLastSyncedAt:[CPDate date]];
        _lastSyncedRevision = _revision;
    }
    else if (anAction === contentDownloadAction)
    {
        [anAction setPath:[self getPath]];
    }
}

- (void)remoteActionDidReceiveResourceRepresentation:(Object)aResult
{
    [WLRemoteObject setDirtProof:YES];
    [[self undoManager] disableUndoRegistration];
    // Take any data received from the POST/PUT/PATCH and update the object correspondingly -
    // in particular we might need any primary key that was generated. We could also get new
    // data for updated_at style fields.

    // At the same time we don't want to overwrite any changes the user made while the request
    // was processing, so we preserve dirty properties here.
    [self updateFromJson:aResult preservingDirtyProperties:YES];
    [[self undoManager] enableUndoRegistration];
    [WLRemoteObject setDirtProof:NO];
}

- (void)remoteActionDidFinish:(WLRemoteAction)anAction
{
    if (anAction === createAction)
    {
        [self remoteActionDidReceiveResourceRepresentation:[anAction result]];

        createAction = nil;
        if ([_delegate respondsToSelector:@selector(remoteObjectWasCreated:)])
            [_delegate remoteObjectWasCreated:self];
    }
    else if (anAction === deleteAction)
    {
        // The previous PK is now gone.
        [self setPk:nil];

        // There is nothing to save anymore.
        [saveAction cancel];
        saveAction = nil;

        // After the object has been deleted, the next call to 'ensureCreated' will
        // create a new object. When that creation happens all the data should be
        // considered dirty to ensure it gets sent with the creation.
        [self makeAllDirty];

        deleteAction = nil;
        [self remoteObjectWasDeleted];
    }
    else if (anAction === saveAction)
    {
        if ([anAction result])
            [self remoteActionDidReceiveResourceRepresentation:[anAction result]];

        saveAction = nil;
        if (_mustSaveAgain)
        {
            _mustSaveAgain = NO;
            [self ensureSaved];
        }
    }
    else if (anAction === contentDownloadAction)
    {
        // Assume whatever was downloaded is the most current info, so nothing gets dirty.
        [WLRemoteObject setDirtProof:YES];
        [[self undoManager] disableUndoRegistration];
        [self updateFromJson:[anAction result]];
        [[self undoManager] enableUndoRegistration];
        [WLRemoteObject setDirtProof:NO];

        contentDownloadAction = nil;
        [self remoteObjectWasLoaded];
    }
}

- (void)remoteObjectWasLoaded
{
    if ([_delegate respondsToSelector:@selector(remoteObjectWasLoaded:)])
        [_delegate remoteObjectWasLoaded:self];
}

- (void)remoteObjectWasDeleted
{
    if ([_delegate respondsToSelector:@selector(remoteObjectWasDeleted:)])
        [_delegate remoteObjectWasDeleted:self];
}

#pragma mark CPObject

- (CPString)description
{
    return "<" + [self class] + " " + [self UID] + (pk ? " " + pk : "") + ">";
}

@end

var WLRemoteObjectClassKey = "WLRemoteObjectClassKey",
    WLRemoteObjectPkKey = "WLRemoteObjectPkKey";

@implementation WLRemoteObject (CPCoding)

- (id)initWithCoder:(CPCoder)aCoder
{
    if (self = [self init])
    {
        pk = [aCoder decodeObjectForKey:@"$pk"];

        if (pk)
        {
            var existingObject = [[self class] instanceForPk:pk];
            if (existingObject)
                return existingObject;
        }

        [_remoteProperties enumerateObjectsUsingBlock:function(aProperty, idx)
            {
                [self setValue:[aCoder decodeObjectForKey:"$" + [aProperty localName]] forKey:[aProperty localName]];
            }];
    }

    return self;
}

- (void)encodeWithCoder:(CPCoder)aCoder
{
    [_remoteProperties enumerateObjectsUsingBlock:function(aProperty, idx)
        {
            [aCoder encodeObject:[self valueForKey:[aProperty localName]] forKey:"$" + [aProperty localName]];
        }];
}

@end

@implementation RemoteProperty : CPObject
{
    CPString            localName @accessors;
    CPString            remoteName @accessors;
    CPValueTransformer  valueTransformer @accessors;
}

+ (id)propertyWithName:(CPString)aName
{
    return [self propertyWithLocalName:aName remoteName:aName transformer:nil];
}

+ (id)propertyWithLocalName:(CPString)aLocalName remoteName:(CPString)aRemoteName
{
    return [self propertyWithLocalName:aLocalName remoteName:aRemoteName transformer:nil];
}

+ (id)propertyWithLocalName:(CPString)aLocalName remoteName:(CPString)aRemoteName transformer:(CPValueTransformer)aTransformer
{
    var r = [RemoteProperty new];
    [r setLocalName:aLocalName];
    [r setRemoteName:aRemoteName];
    [r setValueTransformer:aTransformer];
    return r;
}

- (BOOL)isEqual:(id)anOther
{
    return (anOther !== nil && anOther.isa && [anOther isKindOfClass:RemoteProperty] && anOther.localName == self.localName);
}

- (CPString)description
{
    return "<RemoteProperty " + remoteName + ":" + localName + ">";
}

@end


{'fraction_non_alphanumeric': 0.09417719832825483, 'fraction_numerical': 0.0011322576885292306, 'mean_word_length': 3.018870449678801, 'pattern_counts': {'":': 2, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 34, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1150767', 'n_tokens_mistral': 16967, 'n_tokens_neox': 16075, 'n_words': 5053}