require 'rubygems'
require 'sinatra'
require 'json'
require 'omniauth'
require 'omniauth-twitter'
require 'twitter'
require "sinatra/jsonp"
require_relative 'twitter'

=begin
if request.referrer == "http://example.com/blog/"
  jsonp @@twitter_client.home_timeline.map(&:attrs)
else
  status 401
end
=end

class TwistApp < Sinatra::Base
  helpers Sinatra::Jsonp

  configure do
    set :sessions, true
    set :public_folder, File.dirname(__FILE__) + '/static'
    enable :logging
  end

  use OmniAuth::Builder do
    provider :twitter, ENV['CONSUMER_KEY'], ENV['CONSUMER_SECRET']
  end

  Twitter.configure do |config|
    config.consumer_key = ENV["CONSUMER_KEY"]
    config.consumer_secret = ENV["CONSUMER_SECRET"]
    config.oauth_token = ENV["ACCESS_TOKEN"]
    config.oauth_token_secret = ENV["ACCESS_TOKEN_SECRET"]
  end

  get '/' do
    # erb "<a href='http://localhost:4567/auth/twitter'>Login with twitter</a><br>"
    erb :lists
  end
  
  get '/auth/:provider/callback' do
    erb "<h1>#{params[:provider]}</h1>
         <pre>#{JSON.pretty_generate(request.env['omniauth.auth'])}</pre>"
  end
  
  get '/auth/failure' do
    erb "<h1>Authentication Failed:</h1><h3>message:<h3> <pre>#{params}</pre>"
  end
  
  get '/auth/:provider/deauthorized' do
    erb "#{params[:provider]} has deauthorized this app."
  end
  
  get '/protected' do
    throw(:halt, [401, "Not authorized\n"]) unless session[:authenticated]
    erb "<pre>#{request.env['omniauth.auth'].to_json}</pre><hr>
         <a href='/logout'>Logout</a>"
  end
  
  get '/logout' do
    session[:authenticated] = false
    redirect '/'
  end

  get '/user.?:format?' do
  	json = File.read("static/user.json")
  	user = JSON.parse(json)
  end

  # GET lists/ownerships
  get '/lists.?:format?' do
    jsonp lists = Twitter.lists_owned('ericcandino').map(&:attrs)
  end

  # GET lists/show
  get '/lists/:id.?:format?' do
    jsonp list = Twitter.list('ericcandino', 94894917).map(&:attrs)
  end

  # POST lists/create
  # POST lists/update
  # POST lists/delete

  get '/lists/:list_id/members.?:format?' do
    params[:list_id] = params[:list_id].to_i
    jsonp members = Twitter.list_members(params[:list_id]).map(&:attrs)
  end  

  # get a specific member of a list
  
  # add a person to the list (500 member cap)
  post '/lists/:list_id/members.?:format' do
    list_id = params[:list_id].to_i
    member = params['member']
    list = Twitter.list_subscribe(params[:member][:username], list_id)
    # return 200 & new list obj
  end


  # bulk create members for the list (list/membes/create_all)
  # remove a member from the list

  # List below are used for optimizing searchs (autocomplete)
    # friends list (who the user is following) [array of ids]
    # followers list (who follows the user) [array of ids]
  # users/lookup 100 records at once
  # users/search 1000 results, no exact matches



end

TwistApp.run! if __FILE__ == $0  
