class InvitesController < ApplicationController

  layout 'profile'
  before_filter :require_login, except: [:accept]
  # Invitations message
  INVITATIONS_DEFAULT_MESSAGE = "Hey there, I'd like to invite you to signup for #{Configurations::General.application_name}."

  # It render to invite form(i.e. It will ask user to invite his friend to signup and get paid 1$)
  def show
    @name = current_user.name
    @message = INVITATIONS_DEFAULT_MESSAGE
  end

  # Intialize new object for invite form.
  def new
    @invite = Invite.new
    render layout: false
  end

  # It will create Invite email for the mail Ids user entered and send mails to those Id for signup.
  def create
    @invite = Invite.new invite_params
    @invite.valid?
    unless @invite.errors.messages.has_key?(:invitee_emails)
      @emails = @invite.invitee_emails.split(',').map(&:strip).compact
      invitations = current_user.invites.where(accepted_at: nil, invitee_email: @emails)
      invites = Invite.create((@emails - invitations.map(&:invitee_email)).map {|e| {invitee_email: e}})
      invites.map(&:send_invitation_email)
      respond_to do |format|
        format.js {render 'create'}
      end
    else
      respond_to do |format|
        format.js { render partial: 'form', object: @invite, replace: 'form#new_invite'}
      end
    end
  end

  # Method to accept the Invite and when user click accept it will redirect user to signup page.
  def accept
     @invite = Invite.find_by(invite_token: params[:id])
     unless @invite
       redirect_to root_path, alert: "Invalid URL." and return
     end
     @invite.accept!
     redirect_to root_path(invitation_token: @invite.invite_token)
  end

  private
  def invite_params
    params.required(:invite).permit(:invitee_email, :invite_token, :invitee_emails)
  end

end
