require 'open-uri'
require 'net/http'

class LastFmController < ApplicationController
  before_filter :authorize, :except => [:connect, :autocomplete]
  
  def connect
    unless params[:sid].nil? or params[:token].nil?
      session = Session.find_by_key(params[:sid])
      unless session.nil?
        lastfm_api_session = LastFM::Auth.get_session(:token => params[:token], :api_sig => true)
        session.user.lastfm_key = lastfm_api_session["session"]['key']
        session.user.lastfm_username = lastfm_api_session["session"]['name']
        session.user.save
        render :text => '<script>window.close();</script>'
      else
        return render :text => 'You Don\'t Fool Me'
      end
    else
      return render :text => 'So Much Trouble In The World'
    end
  end
  
  def getinfo
    @res = {}
    user = User.find_by_vkid(params[:mid])
    unless user.lastfm_key.nil?
      render :json => {
        :connected => true,
        :username => user.lastfm_username
      }
    else
      render :json => {
        :connected => false,
        :lastfm_login_url => 'http://www.last.fm/api/auth?api_key='+ LastFM.api_key +
          '&cb=http://'+ request.host << '/lastfm/connect/?sid='+ user.session.key
      }
    end
  end
  
  def listening
    @res = {}
    if params[:artist].nil? or params[:album].nil? or params[:name].nil?
      return render :json => { :status => 'bad params' }
    end
    user = User.find_by_vkid(params[:mid])
    if user.lastfm_key.nil?
      return render :json => {:status => 'lastfm account is not connected', :user => user}
    end
    r = LastFM::Track.update_now_playing(
      :track => params[:name],
      :artist => params[:artist],
      :album => params[:album],
      :trackNumber => params[:position].to_i,
      :duration => params[:length].to_i,
      :sk => user.lastfm_key # Auth session key
    )
    render :json => { :status => r['error'].nil? ? 'success' : r }
  end
  
  def scrobble
    @res = {}
    if params[:artist].nil? or params[:album].nil? or params[:name].nil?
      return render :json => { :status => 'bad params' }
    end
    user = User.find_by_vkid(params[:mid])
    if user.lastfm_key.nil?
      return render :json => { :status => 'lastfm account is not connected', :user => user }
    end
    r = LastFM::Track.scrobble(
      :track => params[:name],
      :timestamp => Time.now.utc.to_i,
      :artist => params[:artist],
      :album => params[:album],
      :trackNumber => params[:position].to_i,
      :duration => params[:length].to_i,
      :sk => user.lastfm_key # Auth session key
    )
    render :json => { :status => r['error'].nil? ? 'success' : r }
  end
  
  def autocomplete
    autocomplete = getSuggestions(params[:query])
    return render :nothing => true if autocomplete.nil?
    suggestions = []
    autocomplete["response"]["docs"].each do |doc|
      suggestions << doc["artist"] unless suggestions.include?(doc["artist"]) or doc["artist"].nil? or doc['restype'] != 6
    end
    render :json => {
      :query => params[:query],
      :suggestions => suggestions.take(5)
    }
  end
  
private
  
  def getSuggestions query
    return nil if query.nil? or query.strip.empty?
    json = ActiveSupport::JSON.decode(open(
      'http://www.last.fm/search/autocomplete' <<
      '?rows=30&q=' << URI.escape(query)
    ).read)
    json.empty? ? nil : json
  end
end