class ExternalMemory::WebServer

  def get_tweet_element_by_tweet_id(source_id, tweet_id)
    json(200, twitter_element_by_tweet_id_or_not_found(source_id, tweet_id).to_json({:element => :full}))
  end

  def get_tweet_element_by_element_id(source_id, element_id)
    json(200, twitter_element_by_element_id_or_not_found(source_id, element_id).to_json({:element => :full}))
  end

  def get_tweet_elements_by_source(source_id)
    source = twitter_source_by_id_or_not_found(source_id)
    tweets = TweetElement.
      with_element.
      by_source(source).
      order_by_timestamp.
      paginate(params[:page], params[:per_page])
    json(
      200,
      {'tweetElements' => tweets.collect { |t| t.to_json }},
      pagination_header(tweets)
    )
  end

  def search_tweet_elements(source_id, search_query)
    twitter_source = twitter_source_by_id_or_not_found(source_id)
    begin
      tweet_elements = search_elements_in_twitter_source(twitter_source, search_query)
      json(
        200,
        {'tweetElements' => tweet_elements.collect { |t| t.to_json }}
      )
    rescue Exception => e
      flash_error('Error while searching')
      json_error(503, 'Error while searching')
    end
  end

  private

  def twitter_source_by_id_or_not_found(source_id)
    not_found_if_empty(Source.by_id(ExternalMemory::Source::TWITTER_TYPE, source_id), 'source', source_id)
  end

  def twitter_element_by_element_id_or_not_found(source_id, element_id)
    source = twitter_source_by_id_or_not_found(source_id)
    not_found_if_empty(TweetElement.with_element.by_source(source).by_element_id(element_id), 'tweet element', element_id)
  end

  def twitter_element_by_tweet_id_or_not_found(source_id, tweet_id)
    source = twitter_source_by_id_or_not_found(source_id)
    not_found_if_empty(TweetElement.with_element.by_source(source).by_tweet_id(tweet_id), 'tweet element', tweet_id)
  end

end
require_relative 'tweet_element_get_declaration'
