class UserController < ApplicationController
  before_filter :authorize
  
  def auth
    @res = {:status => 'hello', :newbie => false}
    user = User.find_by_vkid(params[:mid])
    if user.nil?
      user = User.new
      user.vkid = params[:mid]
      user.lang = 'ru'
      user.save
      @res[:newbie] = true
    end
    
    session = Session.find_or_create_by_user_id(user.id)
    if session.key != session_key
      session.key = session_key
      session.save
      @res[:ok_reload] = true
      render :json => @res
      return
    end
    
    @res[:user] = {
      :id => user.id,
      :name => user.name,
      :email => user.email,
      :vkid => user.vkid,
      :lang => user.lang,
      :lastfm_username => user.lastfm_username,
      :lastfm_login_url => 'http://www.last.fm/api/auth?api_key=' << LastFM.api_key <<
        '&cb=http://' << request.host << ':' << request.port.to_s << '/lastfm/connect/?sid=' << user.session.key
    }
    
    render :json => @res
  end
  
  def settings
    @user = User.find_by_vkid(params[:mid])
    render :partial => 'settings'
  end
  
  def update
    allowed_params = [:name, :email, :lang, :show]
    @res = {}
    
    user = User.find_by_vkid(params[:mid])
    unless params[:params].nil?
      update_params = {}
      params[:params] = params[:params].each{ |k, v| update_params[k.to_sym] = v }
      if (update_params.keys - allowed_params).empty?
        if update_params.include? :show
          update_params[:show] = update_params[:show].map{ |k, v| k.to_sym }
        end
      
        params[:params].each do |k, v|
          user[k] = v
        end
        user.save
      end
    end
    
    @res[:user] = {
      :id => user.id,
      :name => user.name,
      :email => user.email,
      :vkid => user.vkid,
      :lang => user.lang,
      :lastfm_username => user.lastfm_username,
      :lastfm_login_url => 'http://www.last.fm/api/auth?api_key=' << LastFM.api_key <<
        '&cb=http://' << request.host << ':' << request.port.to_s << '/lastfm/connect/?sid=' << user.session.key
    }
    
    render :json => @res
  end
  
  def fav
    @res = {status: 'fail'}
    
    fav = Favorite.new
    if not params[:artist].nil?
      artist = Artist.find(params[:artist]);
      unless artist.nil?
        fav.artist_id = artist.id
        res[:status] = 'added'
      end
    elsif not params[:album].nil?
      album = Album.find(params[:album]);
      unless album.nil?
        fav.album_id = album.id
        res[:status] = 'added'
      end
    elsif not params[:track].nil?
      track = Track.find(params[:track]);
      unless track.nil?
        fav.track_id = track.id
        res[:status] = 'added'
      end
    end
    
    render :json => @res
  end
  
end