class StocksDatatable

  delegate :params, :image_tag,
    :available_products_path, :products_initial_stock_path,
    to: :@view

  def initialize(view, user, showcolumns)
    @view = view
    @current_user = user
    @showcolumns = showcolumns
  end

  def as_json(options = {})

    if @current_user.usertype == 'S'
      total = WarehouseStock.activos.where(:warehouse_id => @current_user.pointsale_id)
    else
      total = AvailableProduct.activos.where(:pointsale_id => @current_user.warehouse_id)
    end

    {
      sEcho: params[:sEcho].to_i,
      iTotalRecords: total.size,
      iTotalDisplayRecords: stock.total_entries,
      aaData: data
    }
  end

private

  def data
    stock.map do | available |
      if available.product.img_product?
        img = available.product.img_product.url(:small)
      else
        img = "/images/small/missing.png"
      end
      category = available.product.categories[0]
      {
        'DT_RowId' => "availableProduct_#{available.id}",
        '0' => '<input class="form-control checkboxes" type="checkbox"/>',
        '1' => (image_tag img),
        '2' => available.product.sku,
        '3' => "#{available.product.name + '<br>' + available.product.display_attributes}",
        '4' => (category.parent_id == 0 ? category.category : category.parent.category),
        '5' => (category.parent_id != 0 ? category.category : ' '),
        '6' => (@showcolumns == "minMax" ? available.stock_min : available.stock),
        '7' => (@showcolumns == "minMax" ? available.stock_max : nil)
      }.compact.reject { |k, v| v.nil? }
    end
  end


  def stock
    @stock ||= fetch_stock
  end

  def fetch_stock
    if @current_user.usertype == 'S'
      stock = WarehouseStock.activos.includes(:product, :categories).where(:warehouse_id => @current_user.warehouse_id).order('products.name')
    else
      stock = AvailableProduct.activos.includes(:product, :categories).where(:pointsale_id => @current_user.pointsale_id).order('products.name')
    end

    stock = stock.page(page).per_page(per_page)

    unless params[:busqueda].blank?
      stock = stock.where("products.sku ilike :search or products.name ilike :search", search: "%#{params[:busqueda]}%").order('products.name')
    end

    stock
  end

  def page
    params[:start].to_i/per_page + 1
  end

  def per_page
    params[:length].to_i > 0 ? params[:length].to_i : 20
  end

  def sort_column
    columns = %w[name]
    columns[params[:iSortCol_0].to_i]
  end

  def sort_direction
    params[:sSortDir_0] == "desc" ? "desc" : "asc"
  end

end
