class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.

  before_filter do
    resource = controller_path.singularize.tr('/', '_').to_sym
    method = "#{resource}_params"
    params[resource] &&= send(method) if respond_to?(method, true)
  end

  before_filter :set_pos_config
  around_filter :user_time_zone, if: :set_pos_config

  protect_from_forgery with: :exception

  ##--- Breadcrum_rails
  add_breadcrumb I18n.t("breadcrumbs.dashboard"), :root_path

  ##--- Restriccion para autentificacion
  before_action :authenticate_user!

  ##--- Notes boxes
  add_flash_types :success, :warning, :danger, :info

  ##--- Parametros permitidos para los usuarios
  before_action :configure_permitted_parameters, if: :devise_controller?

  ##--- Redireccionamiento para los permisos a modulos
  rescue_from CanCan::AccessDenied do |exception|
    redirect_to root_url, alert: exception.message
  end

  ##--- Funciones personalizadas
  def getcounties
    render json: SpmxCounty.where("state_id = ?", params[:state_id])
  end

  def find
    query = params[: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|
        if attribute.present?
          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 attributes_json::json->>'#{attr_type}' ilike '%#{attribute}%'")
        else
          next
        end
      end
    else
      product_name = query
    end

    render json: query.include?(":") ? Product.name_sku_barcode_attribute_like(product_name, attrs_query_string).limit(30).to_json(methods: [:small_img, :display_attributes]) : Product.name_sku_barcode_like(params[:query]).limit(30).to_json(methods: [:small_img, :display_attributes])
  end

  # para special_prices
  def find_sp
    query = params[:query]
    product_name = query

    render json: Product.name_sku_barcode_like_sp(product_name).limit(30).to_json(methods: [:small_img])
  end

  def find_from_stock
    query = params[: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|
        if attribute.present?
          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 attributes_json::json->>'#{attr_type}' ilike '%#{attribute}%'")
        else
          next
        end
      end
    else
      product_name = query
    end

    if current_user.usertype == 'S'
      render json: query.include?(":") ? Warehouse.find(current_user.warehouse_id).products.name_sku_barcode_attribute_like(product_name, attrs_query_string).where("stock > 0").limit(30).to_json(methods: [:small_img, :display_attributes]) : Warehouse.find(current_user.warehouse_id).products.name_sku_barcode_like(params[:query]).where("stock > 0").limit(30).to_json(methods: [:small_img, :display_attributes])
    else
      render json: query.include?(":") ? Pointsale.find(current_user.pointsale_id).products.name_sku_barcode_attribute_like(product_name, attrs_query_string).where("stock > 0").limit(30).to_json(methods: [:small_img, :display_attributes]) : Pointsale.find(current_user.pointsale_id).products.name_sku_barcode_like(params[:query]).where("stock > 0").limit(30).to_json(methods: [:small_img, :display_attributes])
    end
  end

  # rubocop:disable Metrics/BlockNesting
  def find_from_stock_by_pointsale
    if params[:pointsale_id].present?
      id = params[:pointsale_id][2, params[:pointsale_id].length]
      query = params[: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|
          if attribute.present?
            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 attributes_json::json->>'#{attr_type}' ilike '%#{attribute}%'")
          else
            next
          end
        end
      else
        product_name = query
      end

      if params[:pointsale_id].first == 'P'
        render json: query.include?(":") ? Pointsale.find(id).products.name_sku_barcode_attribute_like(product_name, attrs_query_string).where("stock > 0").limit(30).to_json(methods: [:small_img, :display_attributes]) : Pointsale.find(id).products.name_sku_barcode_like(params[:query]).where("stock > 0").limit(30).to_json(methods: [:small_img, :display_attributes])
      else
        render json: query.include?(":") ? Warehouse.find(id).products.name_sku_barcode_attribute_like(product_name, attrs_query_string).where("stock > 0").limit(30).to_json(methods: [:small_img, :display_attributes]) : Warehouse.find(id).products.name_sku_barcode_like(params[:query]).where("stock > 0").limit(30).to_json(methods: [:small_img, :display_attributes])
      end
    else
      render json: {}
    end
  end
  # rubocop:enable Metrics/BlockNesting

  def get_subcategories
    render json: params[:category_id] != '0' ? Category.activos.where("parent_id = ?", params[:category_id]) : Category.activos.where('parent_id != 0')
  end

  def set_pos_config
    @pos_config = PosConfig.first
  end

  def user_time_zone(&block)
    Time.use_zone(@pos_config.time_zone, &block)
  end

  def delete_pre_sales
    PreSale.where(user_id: current_user.id).destroy_all
    respond_to do |format|
      format.json { head :no_content }
    end
  end

  def delete_pre_purchases
    PrePurchase.where(user_id: current_user.id).destroy_all
    # render head :no_content
    respond_to do |format|
      format.json { head :no_content }
    end
  end

  def delete_pre_transfers
    respond_to do |format|
      pre_transfers = PreTransfer.where(user_id: current_user.id)
      pre_transfers.each do |pre|
        # rubocop:disable Style/Next
        if pre.destroy
          stock = pre.origin_is_pointsale == 1 ? AvailableProduct.find_by(pointsale_id: pre.origin_id, product_id: pre.product_id) : WarehouseStock.find_by(warehouse_id: pre.origin_id, product_id: pre.product_id)
          stock.stock += pre.quantity
          stock.save
        end
        # rubocop:enable Style/Next
      end
      format.json { head :ok }
    end
  end

  def get_max_product_id
    render json: Product.maximum(:id).to_i.next
  end

  def get_max_purchaseid_by_pointsale
    prefix = Pointsale.find(params[:pointsale_id]).prefix
    next_id = Purchase.where(pointsale_id: params[:pointsale_id]).count.next

    render json: "#{prefix}-C-#{next_id}"
  end

  def get_max_purchaseid_by_warehouse
    prefix = Warehouse.find(params[:warehouse_id]).prefix
    next_id = Purchase.where(warehouse_id: params[:warehouse_id]).count.next

    render json: "#{prefix}-C-#{next_id}"
  end

  def get_next_sale_code
    pointsale = OpenCashRegister.find(params[:open_cash_register_id]).cash_register.pointsale
    next_id = pointsale.sales.count.next
    render json: "#{pointsale.prefix}-V-#{next_id}"
  end

  def get_next_expense_code
    if current_user.usertype == 'A'
      next_id = Expense.where("expense_code ilike ?", '%ADM%').count.next
      render json: "ADM-E-#{next_id}"
    else
      pointsale = OpenCashRegister.find(params[:open_cash_register_id]).cash_register.pointsale
      next_id = pointsale.expenses.count.next
      render json: "#{pointsale.prefix}-E-#{next_id}"
    end
  end

  def products_by_category_pointsale
    products = Array.new
    products_by_line = Array.new
    category_id = params[:category_id]
    id = params[:pointsale_id][2, params[:pointsale_id].length]

    categories = Category.find(category_id).self_and_descendents

    categories.each do |category|
      products_by_line += category.products
    end

    if params[:pointsale_id].first == 'P'
      Pointsale.find(id).products.each do |p|
        if products_by_line.include?(p)
          products << p
        end
      end
    else
      Warehouse.find(id).products.each do |p|
        if products_by_line.include?(p)
          products << p
        end
      end
    end
    render json: products
  end

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:userid, :first_name, :last_name, :email, :password, :remember_me) }
  end

  def respond_modal_with(*args, &blk)
    options = args.extract_options!
    options[:responder] = ModalResponder
    respond_with(*args, options, &blk)
  end
end
