# -*- encoding : utf-8 -*-
class Public::AnnonceAccountsAuthsController < ApplicationController
  layout "public"

  def new
    
    if params[:r] and params[:r] != ""
      session[:before_auth_url] = nil
    end
    
    @no_search = true
     params[:step] = "login"
    if params[:for_annonce] and params[:for_annonce] != ""
      session[:for_annonce] = true
      
    else
      session[:for_annonce] = nil
      params[:for_annonce] =nil
    end

    @annonce_account = AnnonceAccount.new()
    if cookies[:mlm_token] and @parent = AnnonceAccount.find_parrain(cookies[:mlm_token])
      @annonce_account.parent_code = @parent.mlm_token.upcase

    elsif params[:p] and @parent = AnnonceAccount.find_parrain(params[:p])
      @annonce_account.parent_code = @parent.mlm_token.upcase

    end    
  end

  def facebook_connect_callback

    # Get facebook information
    auth = request.env["omniauth.auth"]
    
    if current_annonce_account
      
      if current_annonce_account.uid == auth['uid']
        redirect_to public_my_account_path, :alert => "Votre compte facebook est déjà lié à ce compte utilisateur Sideplace."
      elsif AnnonceAccount.where(:provider => auth['provider'], :uid => auth['uid']).count > 0
        redirect_to public_my_account_path, :alert => "Votre compte facebook est déjà lié à un compte utilisateur Sideplace."
      else
        @annonce_account = current_annonce_account
        @annonce_account.provider = auth['provider']
        @annonce_account.uid = auth['uid']
        @annonce_account.facebook_token = auth['credentials']['token']
        @annonce_account.save
        @annonce_account.set_facebook_friends
        
        redirect_to public_my_account_path, :notice => "Votre compte facebook a bien été lié à ce compte utilisateur."
      
        
      end
    else
      # Search if already the user already exists
      @annonce_account = AnnonceAccount.where(:provider => auth['provider'], :uid => auth['uid']).first

      # If no user found, create him with callback information contained in auth variable
      if !@annonce_account
        if auth['info'] and @annonce_account = AnnonceAccount.find_by_email(auth['info']['email'])
          @error_in_create = true
          alert = "Il existe déjà un compte sur Sideplace avec l'adresse email de votre compte facebook mais il n'est pas relié à celui-ci. Pour relier votre compte facebook à votre compte Sideplace connectez vous avec celui-ci ci dessous et cliquez sur \"Lier mon compte facebook\""
        
        else
          @annonce_account = AnnonceAccount.new

          # Gestion du parrainage (simplement copier/coller du create)
          if cookies[:mlm_token] and @parent = AnnonceAccount.find_parrain(cookies[:mlm_token])
            @annonce_account.parent_code = @parent.mlm_token.upcase
          elsif params[:p] and @parent = AnnonceAccount.find_parrain(params[:p])
            @annonce_account.parent_code = @parent.mlm_token.upcase
          end

          # Persist Omniauth info
          @annonce_account.provider = auth['provider']
          @annonce_account.uid = auth['uid']
          @annonce_account.facebook_token = auth['credentials']['token']
          @annonce_account.facebook_on_create = true
          @annonce_account.set_facebook_friends

          if auth['info']

            # Account info
            @annonce_account.firstname = auth['info']['first_name']
            @annonce_account.name = auth['info']['last_name']
            @annonce_account.email = auth['info']['email']

            # Retrieve Facebook picture as sideplace avatar
            avatar_url = auth["extra"]["raw_info"]["picture"]["data"]["url"]
            @annonce_account.update_attributes( remote_avatar_url: avatar_url)

            # In the case of facebook connect, we can enable directly the user account
            @annonce_account.enabled = true
            @annonce_account.remote_ip = request.remote_ip
            IpHistory.create(:element => @annonce_account, :annonce_account => @annonce_account, :remote_ip => request.remote_ip)
            # Generate a random password
            require 'securerandom'
            @annonce_account.password = SecureRandom.hex
      
      
      
          end


          # Trying to save him or redirect back if fail
          if !@annonce_account.save
            @error_in_create = true
            alert = "Impossible de vous authentifier avec Facebook car certaines informations indispensables à la création de votre compte n'ont pas été obtenues."
          else
            # If the user is successfully created
            # We send a mail to the parent to notify him
            @parent = AnnonceAccount.find_parrain(@annonce_account.parent_code)

            if @parent
              AnnonceAccountMailer.new_user(@annonce_account).deliver
            end
          end
    
        end
    
      end
    
      if @error_in_create
      
      
        redirect_to new_public_annonce_accounts_auth_path(:fb_alert => true, :email => (auth['info']['email'] if auth['info'])), alert: alert
    
      else
        # Now, the user is retrieved or created

        # Set the user cookie as permanent
        cookies.permanent[:annonce_account_auth_token] = @annonce_account.token

        # Last sign in info
        @annonce_account.last_sign_in_at = Time.now
        @annonce_account.last_sign_in_ip = @annonce_account.current_sign_in_ip
        @annonce_account.current_sign_in_ip = request.remote_ip 
        @annonce_account.provider = auth['provider']
        @annonce_account.uid = auth['uid']
        @annonce_account.facebook_token = auth['credentials']['token']
        IpHistory.create(:element => @annonce_account, :annonce_account => @annonce_account, :remote_ip => request.remote_ip)
        
        # And save him
        @annonce_account.save
        @annonce_account.set_facebook_friends



        # Redirect according session info
        if session[:for_annonce]
          session[:for_annonce] = nil
          redirect_to new_public_annonce_path
        elsif session[:before_auth_url]
          url = session[:before_auth_url]
          session[:before_auth_url] = nil
          redirect_to url
        else
          redirect_to public_my_account_path
        end
      end
    

      
    end
    
  end

  def create
    params[:for_annonce] =nil if params[:for_annonce] == ""
    params[:for_mail] =nil if params[:for_mail] == ""
    @annonce_account = AnnonceAccount.new()
    if cookies[:mlm_token] and @parent = AnnonceAccount.find_parrain(cookies[:mlm_token])
      @annonce_account.parent_code = @parent.mlm_token.upcase

    elsif params[:p] and @parent = AnnonceAccount.find_parrain(params[:p])
      @annonce_account.parent_code = @parent.mlm_token.upcase

    end

    params[:step] = "login"
    @no_search = true
    user = AnnonceAccount.find_by_email(params[:email])
    if user && user.authenticate(params[:password])
      #session[:forum_user_id] = user.id


      if params[:remember_me]
        cookies.permanent[:annonce_account_auth_token] = user.token
      else
        cookies[:annonce_account_auth_token] = user.token
      end
      user.last_sign_in_at = Time.now
      user.last_sign_in_ip = user.current_sign_in_ip
      user.current_sign_in_ip = request.remote_ip 
      IpHistory.create(:element => user, :annonce_account => user, :remote_ip => request.remote_ip)
      user.save(:validate => false)



        if session[:for_annonce]
          session[:for_annonce] = nil
          redirect_to new_public_annonce_path
        elsif session[:before_auth_url]
          url = session[:before_auth_url]
          session[:before_auth_url] = nil
          redirect_to url
        else
          redirect_to public_my_account_path
        end



    else
      flash.now.alert = "Email ou mot de passe incorect"
      render "new"
    end
  end

  def logout
    cookies.delete(:annonce_account_auth_token)
    session[:before_auth_url] = nil
    redirect_to "/", notice: "Déconnecté."
  end
end
