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 = {})
    total =
      if @current_user.usertype == 'S'
        WarehouseStock.activos.where(warehouse_id: @current_user.warehouse_id)
      else
        AvailableProduct.activos.where(pointsale_id: @current_user.pointsale_id.present? ? @current_user.pointsale_id : params[:pointsale])
      end

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

  private

  def data
    stock.map do |available|
      img = available.product.img_product? ? available.product.img_product.url(:small) : "/images/small/missing.png"
      {
        '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' => (available.product.category.parent_id.zero? ? available.product.category.category : available.product.category.parent.category),
        '5' => (available.product.category.parent_id != 0 ? available.product.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
    stock =
      if @current_user.usertype == 'S'
        WarehouseStock.activos.includes(:product, :categories).where(warehouse_id: @current_user.warehouse_id).order('products.name')
      else
        AvailableProduct.activos.includes(:product, :categories).where(pointsale_id: @current_user.pointsale_id.present? ? @current_user.pointsale_id : params[:pointsale]).order('products.name')
      end
    stock = stock.page(page).per_page(per_page)

    search = params[:busqueda]

    unless search.blank?
      stock = stock.where(prepare_query_string(search)).order('products.name')
    end
    stock
  end

  def prepare_query_string(query)
    product_query =
      if query.include? ':' # search with attributes
        query_array = query.split(':')
        @product_name = query_array[0]
        query_array.shift # delete the name of the product from the array to iterate the attributes
        attrs_query_string = ''
        query_array.each do |attribute|
          next if attribute.nil?
          attr_type =
            case attribute[0]
            when 'c'
              'colors'
            when 't'
              'sizes'
            when 'e'
              'styles'
            end
          attribute[0] = "" # delete the attribute type character
          attrs_query_string.concat(" AND products.attributes_json::json->>'#{attr_type}' ilike '%#{attribute}%'")
        end
        "products.sku ilike '%#{@product_name}%' or products.name ilike '%#{@product_name}%' #{attrs_query_string}"
      else
        "products.sku ilike '%#{query}%' or products.name ilike '%#{query}%'"
      end
    product_query
  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
