   twitter = new Twitter require './.twitter-auth.json'
   stream = twitter.stream 'statuses/filter', track: '#apple'
 
-  # Specify index
-  tagsIndex = db.index.get('VTag.name')
-
   # Create event responder
   events = new EventEmitter
 

  # Process tweets and load them to database
  #
  stream.on 'tweet', (data) ->
    db.vertex.create(getTweetModelFromData(data))
    .then (tweet) ->
      # Report tweet saving
      events.emit 'tweet', tweet
      # Save related tags
      saveTags(tweet).then (tags) ->
        events.emit 'tweet and tags', tweet: tweet, tags: tags

  #
  # Processes tweet tags and loads them to database
  #
  saveTags = (tweet) ->
    tweetRid = ridToString tweet['@rid']

    # Loop over all tags in tweet
    Promise.all (mapTagsIn tweet.text, (tagName) ->
      # Find tag key by name in unique index
      tagsIndex.then (tagsIndex) ->
        tagsIndex.get tagName
      # Create or load tag form database
      .then (tag) ->
        if (!tag) then db.vertex.create '@class': 'VTag', name: tagName
        else db.record.get ridToString tag.rid
      # Retrieve tag RID in OrientDB format
      .then (tag) ->
        events.emit 'tag', tag
        ridToString(tag['@rid'] || tag.rid)
      # Create edge from tweet to tag
      .then (tagRid) ->
        db.edge.from(tweetRid).to(tagRid).create '@class': 'E'
      # Emit edge and return tag to be resolved as promise
      .then (edge) ->
        events.emit 'tag to tweet', edge
        tagName
    )

  #
  # Report about tags and tweet saving
  #
  events.on 'tag to tweet', ->
    console.log '.'


#
# Converts data to Twitter model object
#
tweetModel = (data) ->
  # Construct Tweet model
  '@class': 'VTweet'
  text:       data.text
  createdAt:  moment.utc(new Date data.created_at).format 'YYYY-MM-DD HH:mm:ss'
  inReplyTo:  getInReplyTo data
  data:       _.omit data, isExcludedTweetField


#
# Converts data to Twitter user model object
#
# assert.deepEqual {'@class': 'VUser', aA: 1, bB: 2}, userModel {a_a: 1, b_b: 2}
#
userModel = (data) ->
  camelCased = _.zipObject ([changeCase.camelCase(key), value] for key, value of data)
  _.merge {'@class': 'VUser'}, camelCased


# Play with database
