class ApiTwittersController < ApiController

  before_filter :api_signed_in_user

  respond_to :json

  rescue_from 'Twitter::Error::Forbidden' do |exception|
    render :json => { :errors => { :twitter => [exception.to_s] } }, :status => 422
  end

  rescue_from 'Twitter::Error::Unauthorized' do |exception|
    # invalidate current tokens
    current_user.invalidate_user_authorization('twitter')

    render :json => { :errors => { :token => ["is invalid"] } }, :status => 422
  end


  def tweet

    twitter_auth = current_user.user_authorization('twitter')

    raise JamRuby::JamPermissionError unless twitter_auth

    client = Twitter::REST::Client.new do |config|
      config.consumer_key        = Rails.application.config.twitter_app_id
      config.consumer_secret     = Rails.application.config.twitter_app_secret
      config.access_token        = twitter_auth.token
      config.access_token_secret = twitter_auth.secret
    end

    text = params[:message]

    client.update(text)

    render json: {}, status: :ok
  end
end
