class ItemsController < ApplicationController
  active_scaffold :"item" do |conf|
    conf.columns[:unit].form_ui = :select
    conf.columns[:sub_category].form_ui = :select
  end

  def check_availability
    @suppliers = Supplier.order(:name).all
    @selected_supplier = Supplier.find_by_id(params[:supplier_id])
    @items = @selected_supplier.try(:items) || []
    @codes_to_check = params[:codes] || ""
    @codes_to_check_array = @codes_to_check.split("\n").reject { |code| code.strip.blank? }.map(&:strip)
    items_to_check = @items.map { |i| i.code.strip }

    @missing_from_database =  (@codes_to_check_array - items_to_check) || []
    @missing_from_codes = (items_to_check - @codes_to_check_array) || []
  end

  def delete_items
    @suppliers = Supplier.order(:name).all
    @selected_supplier = Supplier.find_by_id(params[:supplier_id])
    @items = @selected_supplier.try(:items) || []
    @codes_to_check = params[:codes] || ""
    @codes_to_check_array = @codes_to_check.split("\n").reject { |code| code.strip.blank? }.map(&:strip)
    items_to_check = @items.map { |i| i.code.strip }

    @items_for_delete = items_to_check & @codes_to_check_array
    Item.where(:code => @items_for_delete).destroy_all

    @not_deleted_items = (@codes_to_check_array - @items_for_delete) || []

    render :template => "items/check_availability"
  end

  def export_import
    @tasks = [ ["Validate items", "validate_items"],
               ["Import items", "import_items"],
               ["Update prices", "update_prices"] ]
  end

  def export_import_post
    @tasks = [ ["Validate items", "validate_items"],
               ["Import items", "import_items"],
               ["Update prices", "update_prices"] ]

    @csv_content = params[:csv_content]

    @error_message = ""
    @output =  []

    if params[:csv_content] == ""
      @error_message = "Format of CSV is wrong (CSV content is empty)"
    else
      begin
        csv_parsed = CSV.parse(params[:csv_content])
      rescue CSV::MalformedCSVError => er
        @error_message = "Format of CSV is wrong (#{er.message})"
      end

      unless csv_parsed.nil?
        csv_file = ItemsHelper::create_csv(csv_parsed)

        begin
          ENV["INPUT"] = csv_file.path

          case params[:task]
          when 'validate_items'
            @output = ItemsHelper::execute_command("rake ribica:validate_items")
            #ItemsHelper::execute_command("rake ribica:reindex")
          when 'import_items'
            @output = ItemsHelper::execute_command("rake ribica:import_items")
            #ItemsHelper::execute_command("rake ribica:reindex")
          when 'update_prices'
            @output = ItemsHelper::execute_command("rake ribica:update_prices")
            #ItemsHelper::execute_command("rake ribica:reindex")
          else
            @error_message = "There is no such task"
          end
        ensure
          csv_file.unlink
        end
      end

      @output = @output.join("<br/>")
    end

    render :template => "items/export_import"
  end
end
