class AvailableProductsDatatable
  delegate :params, :fa_icon, :available_products_path, :number_to_currency, to: :@view

  def initialize(view, pointsale)
    @view = view
    @pointsale = pointsale
  end

  def as_json(*)
    {
      sEcho: params[:sEcho].to_i,
      iTotalRecords: params[:table] == 'in_pointsale' ? @pointsale.products.activos_children.size : products.total_entries,
      iTotalDisplayRecords: products.total_entries,
      aaData: data
    }
  end

  private

  def data
    if params[:table] == 'in_pointsale'
      products.map do |available|
        {
          'DT_RowId' => "available_#{available.id}",
          '0' => '<input class="form-control checkboxes" type="checkbox"/>',
          '1' => available.product.sku,
          '2' => get_display_name(available.product),
          '3' => (available.product.category.parent_id.zero? ? available.product.category.category : available.product.category.parent.category),
          '4' => (available.product.category.parent_id != 0 ? available.product.category.category : ' '),
          '5' => available.stock
        }.compact.reject { |_k, v| v.nil? }
      end
    else
      products.map do |product|
        {
          'DT_RowId' => "product_#{product.id}",
          '0' => '<input class="form-control checkboxes" type="checkbox"/>',
          '1' => product.sku,
          '2' => get_display_name(product),
          '3' => (product.category.parent_id.zero? ? product.category.category : product.category.parent.category),
          '4' => (product.category.parent_id != 0 ? product.category.category : ' '),
          '5' => number_to_currency(product.price_sale, precision: 2)
        }.compact.reject { |_k, v| v.nil? }
      end
    end
  end

  def get_display_name(product)
    name = "<label style='margin-bottom:0px'><strong>#{product.name}</strong></label> <br>"
    name += "#{product.display_attributes} <br>" if product.display_attributes.present?
    name += "<i class='fa fa-barcode'></i>: #{product.barcode} <br>" if product.barcode.present?
    name += "Descripción: #{product.description}" if product.barcode.present?
    name
  end

  def products
    @products ||= fetch_products
  end

  def fetch_products
    products =
      if params[:table] == 'in_pointsale'
        AvailableProduct.joins(:product, :categories).activos.where(pointsale_id: params[:id]).activos
      else
        products_in_pointsale = @pointsale.products.activos_children.pluck(:id)
        Product.joins(:category).activos_children.where.not(id: products_in_pointsale).order('products.name')
      end

    products = products.page(page).per_page(per_page)

    search = params[:busqueda]

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

    products
  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
