class ProductsDatatable
  delegate :params, :link_to, :number_to_currency, :image_tag,:fa_icon,
    :products_path, :edit_product_path, :product_update_status_path, :product_prices_path,
    :available_products_path, :available_product_edit_price_path, :product_edit_variants_path,
    to: :@view
  def initialize(view, user)
    @view = view
    @current_user = user
  end

  def as_json(options = {})
    {
      sEcho: params[:sEcho].to_i,
      iTotalRecords: Product.vigentes_parents.size,
      iTotalDisplayRecords: products.total_entries,
      aaData: data
    }
  end

private

  def data
    products.map.with_index do |product, index|
      if product.img_product?
        img = product.img_product.url(:medium)
      else
        img = "/images/small/missing.png"
      end
      is_product_available = product.available_in_pointsale?(@current_user.pointsale_id)
      product_available = product.get_available_in_pointsale(@current_user.pointsale_id) if is_product_available
      [
        (index +1),
        (image_tag img),
        "<label>#{product.name} </label> <br>  SKU: <b> #{product.sku} </b>
          #{ '<i class="fa fa-cubes font-yellow-gold"></i>' if product.is_parent }
          <br>" + (product.parent_id.nil? ? "" : "<small>#{product.display_attributes}</small><br>") + "<i class='fa fa-barcode'></i>: <b> #{product.barcode} </b>  <br>
          <p> #{product.description} </p>",
        (@current_user.usertype == 'A' ? (product.is_in_dollars? ? "#{number_to_currency(product.price_base_dollars, precision: 2)} USD" : "#{number_to_currency(product.price_base, precision: 2)} MXN") : nil),
        "<h3> #{number_to_currency(product.get_price_sale(@current_user.pointsale_id), precision: 2)}</h3>
          #{ is_product_available && (product_available && !product_available.price_sale.nil?) && @current_user.usertype == 'G' ? ('Precio de venta base <br>' + number_to_currency(product.price_sale, precision: 2) ) : ''}",
        product.categories[0].category,
        product.active? ? "<i class='fa fa-check fa-2 font-green'></i>" : "<i class='fa fa-times fa-2 font-red'></i>",
        get_actions(@current_user.usertype, product, is_product_available, product_available)
      ].compact
    end
  end


  def products
    @products ||= fetch_products
  end

  def fetch_products
    products = Product.vigentes_parents.includes(:categories)
    if @current_user.usertype == 'G'
      products = Product.activos_children
    end
    products = products.page(page).per_page(per_page)
    unless params[:busqueda].blank?
      products = products.where("sku ilike :search or name ilike :search", search: "%#{params[:busqueda]}%")
    end
    products
  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

  def get_actions(usertype, product, is_product_available, product_available)
    links = '<div class="clearfix">'
    links += link_to(fa_icon('search'), product, {class: 'btn btn-icon-only default filtros', :title=>"Ver producto"})

    if usertype == 'G'
      links += (link_to(fa_icon('dollar'), available_product_edit_price_path(product_available), { :remote => true, class: 'btn btn-icon-only green-dark', :title=>"Cambiar precio"})) if is_product_available
    elsif usertype == 'A'
      links += link_to(fa_icon('edit'), edit_product_path(product), {class: 'btn btn-icon-only btn-primary filtros', :title=>"Modificar producto"})
      links += link_to(fa_icon('copy'), product_edit_variants_path(product.id), {:class => 'btn btn-icon-only btn-info filtros', :title=>"Modificar variantes del producto"}) if product.presentation
      links += link_to(fa_icon('list-alt'), product_prices_path(product),  {:remote => true, :class => 'btn btn-icon-only green-dark', :title=>"Precios en punto de venta"})
      links += (link_to(fa_icon('toggle-off'), product_update_status_path(product),  :class => 'btn btn-icon-only default', :title=>"Desactivar producto", data: { confirm: '¿Esta seguro de desactivar el producto?', method: 'post'})) if product.active?
      links += (link_to(fa_icon('toggle-on'), product_update_status_path(product),  :class => 'btn btn-icon-only green-jungle', :title=>"Activar producto", data: { confirm: '¿Esta seguro de activar el producto?', method: 'post'})) if product.inactive?
      links += (link_to(fa_icon('trash-o'), product, :class => 'btn btn-icon-only btn-danger', :title=>"Eliminar producto", data: { confirm: '¿Esta seguro de eliminar el producto?', method: :delete})) if product.can_be_deleted?
    end
    links += '</div>'
    return links
  end
end
