class Public::NeedsController < ApplicationController

  layout "public"

  before_filter :auth_customer
  before_filter :check_enabled


  before_filter :build_category_tree, only:[:index,:new,:create,:edit,:update]
  before_filter :check_owner, only: [:destroy,:edit,:update]

  def index

    # Get only public needs
    @needs = Need.shared
    @needs = @needs.domain_in(current_customer.domain_ids)

    # filters default value
    params[:o] ||= 'created-desc'
    params[:r] ||= 6

    # Include search in the query
    if(params[:q] != '')
      @needs = @needs.search(params[:q])
    end

    if(params[:c] and params[:c] != '')
      @category = NeedCategory.find(params[:c])
      ids =  @category.child_ids
      @needs = @needs.where(category_id: ids)
    end

    if(params[:s] and params[:s] != '')
      @needs = @needs.where(state: params[:s])
    end

    # Include order in the query
    case params[:o]
    when 'alpha-asc'
      @needs = @needs.order(title: :asc)
    when 'alpha-desc'
      @needs = @needs.order(title: :desc)
    when 'wishes-asc'
      @needs = @needs.with_wishes_count.order('wishes_count ASC')
    when 'wishes-desc'
      @needs = @needs.with_wishes_count.order('wishes_count DESC')
    when 'created-asc'
      @needs = @needs.order(created_at: :asc)
    when 'created-desc'
      @needs = @needs.order(created_at: :desc)
    when 'comments-asc'
      @needs = @needs.with_messages_count.order('messages_count ASC')
    when 'comments-desc'
      @needs = @needs.with_messages_count.order('messages_count DESC')
    end

    # Paginate
    @needs = @needs.page(params[:page]).per(params[:r])


    # Define order select options
    @orders = {
      "Les plus récents" => 'created-desc',
      "Les plus populaires" => 'wishes-desc',
      "Les plus commentés" => 'comments-desc',
      "Alphabétique (de A à Z)" => 'alpha-asc',
      "Alphabétique (de Z à A)" => 'alpha-desc'
    }


  end


  def download_devis
    @need = Need.find(params[:need_id])

    if @need.author.id != current_customer.id
      flash[:error] = "Vous n'êtes pas le propriétaire"
      return redirect_to :back
    end

    send_file @need.devis.file.path, filename: "proposition-need-#{@need.id}.#{@need.devis.file.extension}"
  end


  def new
    @need = Need.new()
  end

  def destroy
    @need = Need.find(params[:id])
    if(@need.destroy)
      flash[:notice] = "Besoin supprimé avec succès."
    end
    redirect_to public_my_account_path
  end

  def edit
    @need = Need.find(params[:id])
  end

  def show
    @need = Need.find(params[:id])
    @comment = Message.new()
    @comments = @need.messages.order(created_at: :desc).page params[:page]
  end

  def update
    @need = Need.find(params[:id])
    if @need.update_attributes(need_params)
      flash[:notice] = "Besoin sauvegardé avec succès."
      redirect_to public_my_account_path
    else
      render :action => "edit"
    end
  end

  def create
    @need = Need.new(need_params)
    @need.author = current_customer

    if !@need.devis? && !@need.note?
      flash[:error] = "Vous devez joindre une proposition au format PDF ou au moins préciser son prix dans le champ d'information"
      return render :action => "new"
    end

    if @need.save

      @wish = Wish.new
      @wish.customer = current_customer
      @wish.need = @need
      @wish.devis = @need.devis
      @wish.note = @need.note
      @wish.save


      flash[:notice] = "Votre besoin à été créé avec succès."
      redirect_to public_my_account_path
    else
      render :action => "new"
    end
  end



  def wish
    @need = Need.find(params[:id])
    admins = Admin.where.not(email: nil)
    if (!@need.customers.include?(current_customer))
      @need.customers << current_customer
      flash[:notice] = "Vous avez signalé votre intérêt pour ce besoin"
      # Find all admins with email

      admins.each do |admin|
        AdminMailer.customer_interested(admin, @need, current_customer).deliver
      end

    else
      @need.customers.delete(current_customer)
      flash[:error] = "Vous n'êtes maintenant plus intéressé par ce besoin"
      admins.each do |admin|
        AdminMailer.customer_disinterested(admin, @need, current_customer).deliver
      end
    end
    redirect_to :back
  end

  private

  def build_category_tree
    @tree = NeedCategory::create_tree(NeedCategory.domain_in(current_customer.domain_ids))
  end

  def need_params
    params.require(:need).permit(:title, :note, :devis, :description, :category_id)
  end

  def check_owner
    @need = Need.find(params[:id])
    if !@need.author or @need.author.id != current_customer.id
      flash[:error] = "Ce besoin ne vous appartient pas"
      redirect_back_or_default :root
    end
  end

end
