# -*- coding: utf-8 -*-

require 'builder'

class UsersController < ApplicationController
  before_filter :signed_in_user,
                only: [:index, :edit, :update, :destroy]
  before_filter :correct_user,   only: [:edit, :update]
  before_filter :admin_user,     only: :destroy

  rescue_from 'JamRuby::PermissionError' do |exception|
    @exception = exception
    render :file => 'public/403.html', :status => 403, :layout => false
  end
  
  def index
    @users = User.paginate(page: params[:page])
  end

  def show
    @user = User.find(params[:id])
  end

  def new
    @invited_user = load_invited_user(params)

    if !@invited_user.nil? && @invited_user.accepted
      # short-circuit out if this invitation is already accepted
      render "already_signed_up", :layout => 'landing'
      return
    end
    @signup_postback = load_postback(@invited_user)

    load_location(request.remote_ip)

    @user = User.new
    @user.musician = true # default the UI to musician as selected option

    # preseed the form with the invited email as a convenience to the user
    unless @invited_user.nil?
      @user.email = @invited_user.email
    end

    render :layout => 'landing'
  end

  def create

    @invited_user = load_invited_user(params)
    @signup_postback = load_postback(@invited_user)

    @user = User.new

    # check recaptcha; if any errors seen, contribute it to the model
    unless verify_recaptcha(:model => @user, :message => "recaptcha")
      render 'new', :layout => 'landing'
      return
    end

    instruments = fixup_instruments(params[:jam_ruby_user][:instruments])

    birth_date = fixup_birthday(params[:jam_ruby_user]["birth_date(2i)"], params[:jam_ruby_user]["birth_date(3i)"], params[:jam_ruby_user]["birth_date(1i)"])
    location = { :country =>  params[:jam_ruby_user][:country], :state =>  params[:jam_ruby_user][:state], :city =>  params[:jam_ruby_user][:city]}
    terms_of_service = params[:jam_ruby_user][:terms_of_service].nil? ? false : true
    subscribe_email = params[:jam_ruby_user][:subscribe_email].nil? ? false : true
    musician = params[:jam_ruby_user][:musician]


    @user = UserManager.new.signup(request.remote_ip,
                                    params[:jam_ruby_user][:first_name],
                                    params[:jam_ruby_user][:last_name],
                                    params[:jam_ruby_user][:email],
                                    params[:jam_ruby_user][:password],
                                    params[:jam_ruby_user][:password_confirmation],
                                    terms_of_service,
                                    subscribe_email,
                                    instruments,
                                    birth_date,
                                    location,
                                    musician,
                                    nil, # we don't accept photo url on the signup form yet
                                    @invited_user,
                                    ApplicationHelper.base_uri(request) + "/confirm")

    # check for errors
    if @user.errors.any?
      # render any @user.errors on error
      load_location(request.remote_ip, location)
      gon.signup_errors = true
      gon.musician_instruments = instruments
      render 'new', :layout => 'landing'
    else
      sign_in @user

      if @user.musician
        redirect_to :action => :congratulations_musician, :type => 'Native'
      else
        redirect_to :action => :congratulations_fan, :type => 'Native'
      end

    end
  end

  def congratulations_fan
    render :layout => "landing"
  end

  def congratulations_musician
    render :layout => "landing"
  end

  def downloads
    render :layout => "landing"
  end

  def signup_confirm
    signup_token = params[:signup_token]

    @user = UserManager.new.signup_confirm(signup_token, request.remote_ip)

    if !@user.nil? && !@user.errors.any?
      UserMailer.welcome_message(@user).deliver
      sign_in @user
      redirect_to :client
    elsif !@user.nil?
      # new user with validation errors;
      logger.debug("#{@user} has errors. can not sign in until remedied.  #{@user.errors.inspect}")

    end
    # let page have signup_token in javascript
    gon.signup_token = signup_token

    # let errors fall through to signup_confirm.html.erb
  end

  def edit
  end

  def update
    if @user.update_attributes(params[:jam_ruby_user])
      flash[:success] = "Profile updated"
      sign_in @user
      redirect_to @user
    else
      render 'edit'
    end
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User destroyed."
    redirect_to users_url
  end

  def request_reset_password
    render 'request_reset_password', :layout => 'landing'
  end
  
  def reset_password
    begin
      @reset_password_email = params[:jam_ruby_user][:email]

      if @reset_password_email.empty?
        @reset_password_error = "Please enter an email address above"
        render 'request_reset_password', :layout => 'landing'
        return
      end

      @user = User.reset_password(@reset_password_email, ApplicationHelper.base_uri(request))
      render 'sent_reset_password', :layout => 'landing'
    rescue JamRuby::JamArgumentError
      # Dont tell the user if this error occurred to prevent scraping email addresses.
      #@reset_password_error = "Email address not found"
      render 'sent_reset_password', :layout => 'landing'
    end
  end
  
  def reset_password_token
    render 'reset_password_token', :layout => 'landing'
  end
  
  def reset_password_complete
    begin
      User.set_password_from_token(params[:jam_ruby_user][:email], params[:jam_ruby_user][:token], 
        params[:jam_ruby_user][:password], params[:jam_ruby_user][:password_confirmation])
      render 'reset_password_complete', :layout => 'landing'
    rescue JamRuby::JamArgumentError
      @password_error = "Entries don't match or are too short"
      params[:email] = params[:jam_ruby_user][:email]
      params[:token] = params[:jam_ruby_user][:token]
      render 'reset_password_token', :layout => 'landing'
    end
  end

  def finalize_update_email
    # this corresponds to when the user clink a link in their new email address to configure they want to use it,
    # and verify their new address is real
    token = params[:token]

    gon.ensure = true
    gon.update_email_token = token

    render :layout => 'landing'
  end

  def jnlp
    headers["Content-Type"] = "application/x-java-jnlp-file"
    headers["Cache-Control"] = "public"
    headers["Content-Disposition"] = "attachment;filename='ping#{params[:isp]}.jnlp'"
    jnlp = ''
    xml = Builder::XmlMarkup.new(:indent => 2, :target => jnlp)
    xml.instruct!
    jnlpurl = isp_ping_url(:isp => params[:isp], 
                           :format => :jnlp, 
                           :host => 'www.jamkazam.com', 
                           :port => '80')
    xml.jnlp(:spec => '1.0+', 
             :href => jnlpurl, 
             :codebase => "http://www.jamkazam.com/isp") do
      xml.information do
        xml.title 'Ping'
        xml.vendor 'JamKazam'
      end
      xml.resources do
        xml.j2se(:version => "1.6+", :href => "http://java.sun.com/products/autodl/j2se")
        xml.jar(:href => 'http://www.jamkazam.com/isp/ping.jar', :main => 'true')
      end
      xml.tag!('application-desc', 
               :name => "Ping", 
               'main-class' => "com.jamkazam.ping.Ping", 
               :width => "400", 
               :height => "600") do
        xml.comment!('usage: Ping [label=]addr[:port] ... [-c <count>] [-s <size>] -u <url> -i <isp> [-a]')
        xml.argument('foo=etch.dyndns.org:4442') 
        xml.argument('bar=etch.dyndns.org:4442') 
        xml.argument("-uhttp://www.jamkazam.com#{isp_scoring_path}") 
        xml.argument("-i#{params[:isp]}") 
        xml.argument('-a') 
      end
      xml.update(:check => 'background')
    end
    send_data jnlp, :type=>"application/x-java-jnlp-file" 
  end

  def isp
    @isps = {
      'tw' => ['Time Warner', 'tw.jpg'],
      'vz' => ['Verizon', 'vz.png'],
      'att' => ['AT&T', 'att.png'],
      'cc' => ['Comcast', 'cc.png'],
      'other' => ['Other', 'other.jpg']
    }
    render :layout => "landing"
  end

  private

  def correct_user
    @user = User.find(params[:id])
    redirect_to(root_url) unless current_user?(@user)
  end

  def admin_user
    redirect_to(root_url) unless current_user.admin?
  end

  # the User Model expects instruments in a different format than the form submits it
  # so we have to fix it up.
  def fixup_instruments(original_instruments)
    # if an instrument is selected by the user in the form, it'll show up in this array
    instruments = []

    # ok, sweep through all the fields submitted, looking for selected instruments.
    # also, make up priority because we don't ask for it (but users can fix it later on their profile)
    priority = 0
    unless original_instruments == nil
      original_instruments.each do |key, value|
        if !value["selected"].nil?
          instruments << { :instrument_id => key, :proficiency_level => value["proficiency"].to_i, :priority => priority }
          priority = priority + 1
        end
      end
    end

    return instruments
  end

  # the User Model expects instruments in a different format than the form submits it
  # so we have to fix it up.
  def fixup_birthday(month, day, year)
    if month.blank? || day.blank? || year.blank?
      # invalid birthdate, so return nil
      return nil
    end

    return Date.new(year.to_i, month.to_i, day.to_i)
  end

  def load_invited_user(params)
    # check if this an anonymous request, or result of invitation code
    invitation_code = params[:invitation_code]

    invited_user = nil
    unless invitation_code.nil?
      # we only want to find invitations that have not been accepted
      invited_user = InvitedUser.find_by_invitation_code(invitation_code)
    end
    return invited_user
  end

  def load_location(remote_ip, location = nil)
    @location = location

    if @location.nil?
      @location = MaxMindManager.lookup(remote_ip)
    end

    @location[:country] = "US" if @location[:country].nil?

    # right now we only accept US signups for beta
    @countries = MaxMindManager.countries()
    # populate regions based on current country
    @regions = MaxMindManager.regions(@location[:country])
    @cities = @location[:state].nil? ? [] : MaxMindManager.cities(@location[:country], @location[:state])
  end

  def load_postback(invited_user)
    if invited_user.nil?
      signup_path
    else
      signup_path + "?invitation_code=" + invited_user.invitation_code
    end
  end
end
