# coding: utf-8
class Admin::ProductsController < Admin::AdminController

  # GET /admin/resources
  def index
    @search = SearchForm.new(params)
    @products = Product.search(
        Riddle.escape(@search.text),
        with: @search.to_hash,
        select: 'id, code, manufacturer_id, catalogue_category_id, published, title',
        order: 'updated_at DESC',
        ignore_default: true
    ).page(params[:page]).per(10)
  end

  # GET /admin/resources/new
  def new
    @product = Product.new
  end

  def new_from_copy
    @product = Product.find(params[:product_id]).new_from_copy
    render 'new'
  end

  # GET /admin/resources/1/edit
  def edit
    @product = Product.find(params[:id])
  end

  # POST /admin/resources
  def create
    @product = Product.new(params[:product])
    if @product.save
      redirect_to admin_products_path, notice: view_context.notice_message
    else
      render action: 'new'
    end
  end

  # PUT /admin/resources/1
  def update
    @product = Product.find(params[:id])
    if @product.update_attributes(params[:product])
      redirect_to admin_products_path, notice: view_context.notice_message
    else
      render 'edit'
    end
  end

  # DELETE /admin/resources/1
  def destroy
    @product = Product.find(params[:id])
    @product.destroy

    redirect_to admin_products_url, notice: view_context.notice_message
  end

  def typeahead_get_data
    query = params['q'] || ''

    result = Product.search(
        Riddle.escape(query),
        limit: 10,
        select: 'id, title'
    )

    render :json => result
  end

  class SearchForm
    attr_accessor :text, :manufacturer_id, :catalogue_category_id, :published

    def initialize params
      @text = params[:text] unless params[:text].nil? || params[:text].blank?
      @manufacturer_id = params[:manufacturer_id] unless params[:manufacturer_id].nil? || params[:manufacturer_id].blank?
      @catalogue_category_id = params[:catalogue_category_id] unless params[:catalogue_category_id].nil? || params[:catalogue_category_id].blank?
      if not (params[:published].nil? || params[:published].blank?)
         @published = true if params[:published] =~ (/^(true|t|yes|y|1)$/i)
         @published = false if params[:published] =~ (/^(false|f|no|n|0)$/i)
      end
    end

    def text
      @text || ''
    end

    def to_hash
      result = {}
      result[:manufacturer_id] = manufacturer_id unless manufacturer_id.nil?
      result[:catalogue_category_id] = catalogue_category_id unless catalogue_category_id.nil?
      result[:published] = published unless published.nil?
      result
    end

  end

end