class Public::WishesController < ApplicationController
  layout "public"

  before_filter :auth_customer
  before_filter :check_enabled

  def new
    @wish = Wish.new(:qte => 1)
    @need = Need.find(params[:need_id])
    @wish.need = @need
  end

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

  def create
    @wish = Wish.new
    @need = Need.find(params[:need_id])

    if (!@need.customers.include?(current_customer))
      @wish.update_attributes(wishes_params)
      @wish.customer = current_customer

      @wish.need = Need.find(params[:need_id])
      if @wish.save
        admins = Admin.where.not(email: nil)
        admins.each do |admin|
          AdminMailer.customer_interested(admin, @need, current_customer).deliver
        end

        flash[:success] = "Intérêt enregistré, merci pour votre participation"
        redirect_to public_need_path(@need)
      else

        render 'new'
      end

    else
      flash[:error] = "Vous êtes déjà intéressé par ce besoin"
      redirect_to public_need_path(@need)


    end


  end

  def update

    @wish = current_customer.wishes.find(params[:id])
    @need = @wish.need
    @wish.update_attributes(wishes_params)
    if @wish.save
      redirect_to public_need_path(@need)
    else
      render 'new'
    end
  end


  def destroy


    @wish = Wish.find(params[:id])
    @need = @wish.need
    @need.customers.delete(current_customer)

    admins = Admin.where.not(email: nil)
    admins.each do |admin|
      AdminMailer.customer_disinterested(admin, @need, current_customer).deliver
    end
    flash[:success] = "Vous n'êtes plus intéressé par ce besoin"
    redirect_to public_need_path(@need)


  end

  def download_devis

    @wish = Wish.find(params[:id])
    @need = @wish.need

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

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


  def wishes_params
    params.require(:wish).permit(:devis, :note, :need_id, :qte)
  end

end
