#require 'Nokogiri'

class Admin::FoodsController < ApplicationController
  #skip_before_filter :verify_authenticity_token
  before_filter :authenticate_admin!

  def index
    @foods = Food.all
  end

  def show
    @food = Food.find(params[:id])
    @categories = @food.categories
  end

  def new
    @food = Food.new
    @categories = Category.all
  end

  def create
    @food = Food.new(food_params)
    categories = params[:categories]
    @food.categories << Category.find(categories.map(&:to_i))
    @food.save!
    redirect_to :action => 'index', format: 'html'
    #render :status=>200, :json=>{:c=>200, :d=>@food}
  end

  def edit
    @food = Food.find(params[:id])
    @categories = Category.all
    @current_categories = @food.categories.map(&:id)
    if not @current_categories
      @current_categories = []
    end
  end

  def update
    fod = params[:food]
    @food = Food.find(params[:id])
    @food.title = fod[:title]
    @food.cover = fod[:cover]
    @food.desc = fod[:desc]
    @food.body = fod[:body]
    @food.price = fod[:price].to_f

    #doc = Nokogiri::HTML( @food.body )
    #img_srcs = doc.css('img').map{ |i| i['src'] }
    #puts img_srcs

    categories = params[:categories]
    @food.categories.destroy_all
    @food.categories << Category.find(categories.map(&:to_i))
    @food.save!
    redirect_to :action => 'index', format: 'html'
  end

  private
  def food_params
    params.require(:food).permit(:title, :body, :price, :category, :cover, :desc)
  end

end
