module Suppliers
  class TablesController < Suppliers::ApplicationController
    # GET /tables
    # GET /tables.json
    def index
      @tables = Table.for_supplier(current_supplier, page: params[:page], per_page: params[:per_page] || 25, from_number: params[:from_number], to_number: params[:to_number])
      @tables.include_relation(:section)

      render json: @tables
    end

    # GET /tables/1
    # GET /tables/1.json
    def show
      @table= Table.find_by_supplier_id_and_id!(current_supplier.id, params[:id])

      render json: @table
    end

    # GET /tables/new
    # GET /tables/new.json
    def new
      @table = Table.new
      @table.section_id = params[:section_id].presence

      render json: @table
    end

    # GET /tables/1/edit
    def edit
      @table = Table.find(params[:id])
    end

    # POST /tables
    # POST /tables.json
    def create
      @table = Table.new(table_params)
      @table.supplier = current_supplier

      if @table.save
        render json: @table, status: :created
      else
        render json: {errors: @table.errors}, status: :unprocessable_entity
      end
    end

    # PUT /supplier/tables/1
    # PUT /supplier/tables/1.json
    def update
      @table= Table.find_by_supplier_id_and_id!(current_supplier.id, params[:id])

      if @table.update_attributes(table_params)
        render json: @table
      else
        render json: {errors: @table.errors}, status: :unprocessable_entity
      end
    end

    # DELETE /tables/1
    # DELETE /tables/1.json
    def destroy
      @table= Table.find_by_supplier_id_and_id!(current_supplier.id, params[:id])
      @table.destroy

      head :no_content
    end

    def qr_codes
      @tables = Table.for_supplier(current_supplier, from_number: params[:from_number], to_number: params[:to_number])
      @tables.select!{|t| t.section_id == params[:section_id]} if params[:section_id].present?
      @tables.select!{|t| t.id == params[:table_id]} if params[:table_id].present?
      render layout: 'qr_sheet'
    end

    private

    def table_params
      permitted_attributes = [:number, :section_id, :position_x, :position_y, :width, :height]
      # do not raise in development and test for json communication
      if request.format.json?
        params.require(:table).slice(*permitted_attributes).permit!
      else
        params.require(:table).permit permitted_attributes
      end
    end
  end
end
