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



  before_action :init_admin_menu

  before_action :qi_menu
  before_action :set_navbar_dropdown

  def qi_menu(sym=nil)

    if @qi_menus
      if !sym
        sym = controller_name.to_s.singularize.tableize.downcase.to_sym
      end

      if @qi_menus[sym.to_sym]
        @qi_menu_active = sym.to_sym
      else
        @qi_menus.each do |k, v|
          if v[:elements] and v[:elements][sym.to_sym]
              @qi_menu_active = k
              @qi_menu_sub_menu_active = sym.to_sym
            break
          end



        end


      end
    end
  end


  def init_admin_menu
    if current_admin


      @qi_menus = {}

      set_admin_menu
    end
  end

  def set_admin_menu



    set_big_menu :clients, "Clients", admin_p_customers_path, "address-book-o", "#016699"

    set_sub_menu :clients, :p_customers, "Clients", admin_p_customers_path if current_admin.has_permission?("customers")

    set_sub_menu :clients, :p_customer_cats, "Catégories clients", admin_p_customer_cats_path if current_admin.has_permission?("p_customer_cats")

    


    set_big_menu :stocks, "Produits", admin_p_products_path, "cubes", "#718197"

    if current_admin.has_permission?("products")
      set_sub_menu :stocks, :p_products, "Produits", admin_p_products_path
      set_sub_menu :stocks, :p_product_refs, "Références", admin_p_product_refs_path
      set_sub_menu :stocks, :p_articles, "Articles", admin_p_articles_path
      # set_sub_menu :stocks, :promos_p_products, "Offres spots", promos_admin_p_products_path

    end

    if current_admin.has_permission?("product-cats")
      set_sub_menu :stocks, :p_product_cats, "Catégories produits", admin_p_product_cats_path
      # set_sub_menu :stocks, :p_product_sub_cats, "Sous catégories produits", admin_p_product_sub_cats_path

    end

    

    if current_admin.has_permission?("brands")
      set_sub_menu :stocks, :s_brands, "Marques", admin_s_brands_path


    end

    if current_admin.has_permission?("fournisseurs")
      set_sub_menu :stocks, :p_fournisseurs, "Fournisseurs", admin_p_fournisseurs_path


    end

    if current_admin.has_permission?("stocks")
      set_sub_menu :stocks, :stock_alias, "Stocks", admin_line_stocks_path


    end

    if current_admin.has_permission?("boutique")
      set_sub_menu :stocks, :p_product_colors, "Couleurs"
      set_sub_menu :stocks, :p_article_serial_nums, "Numeros série"
      set_sub_menu :stocks, :p_serial_num_types, "Types de Numero série"
      set_sub_menu :stocks, :p_product_ref_specs, "Specs"
      set_sub_menu :stocks, :p_spec_values, "Valeur de specs"
      set_sub_menu :stocks, :p_grades, "Grades" if PGrade::ACTIVATED
      set_sub_menu :stocks, :p_product_powers, "Types de chargeurs"
      set_sub_menu :stocks, :p_product_zones, "Zones produits"
      

    end





    set_big_menu :ventes, "Commandes", admin_p_customer_sheets_path, "shopping-cart", "#518889"

    set_sub_menu :ventes, :p_customer_sheets, "Demande de commande", admin_p_customer_sheets_path

    if false
      PriceDocumentType.where(:label => PriceDocument::SALES).order("id DESC").all.each do |p_document_type|

        set_sub_menu :ventes, :"p_document_type_#{p_document_type.label.to_s.to_slug}", p_document_type.label, admin_price_documents_path(:price_document_type_id => p_document_type.id)

      end

      set_sub_menu :ventes, :price_documents_all, "Tous documents", admin_price_documents_path
    end




    if current_admin.has_permission?("bills")
      set_big_menu :documents, "Achats", admin_price_documents_path(:price_document_type_id =>6, :purchase => true), "file-text-o", "#d97941"

      set_sub_menu :documents, :buy_lists, "TdB achats"

      set_sub_menu :documents, :line_stocks, "Lignes de stock", admin_line_stocks_path
      set_sub_menu :documents, :stock_movements, "Mouvements de stock manuel", admin_stock_movements_path


      PriceDocumentType.where(:label => PriceDocument::PURCHASES).order("id DESC").all.each do |p_document_type|
        set_sub_menu :documents, :"p_document_type_#{p_document_type.label.to_s.to_slug}", p_document_type.label, admin_price_documents_path(:price_document_type_id => p_document_type.id)

      end
      
      set_sub_menu :documents, :"p_document_type_reponse_fournisseur", "Réponses fournisseurs", admin_price_documents_path(:price_document_type_id => 2)




    end


    if current_admin.has_permission?("payments")
      set_big_menu :payments, "Paiements", admin_p_payments_path, "eur", "#ED6353"

      set_sub_menu :payments, :p_payments, "Paiements", admin_p_payments_path
      set_sub_menu :payments, :p_payment_types, "Types de paiements", admin_p_payment_types_path
      set_sub_menu :payments, :p_compta_exports, "Exports comptables", admin_p_compta_exports_path


    end


    if current_admin.has_permission?("stats-commercial")


      set_big_menu :statistiques, "Stats", commercial_admin_dashboards_path, "bar-chart", "#6C5B7B"


    end
    

  end

  def set_product_display

    if session[:display_products] == nil
      session[:display_products] = true
    end
  end

  def set_big_menu(sym, name, link, icon, color)

    @qi_menus[sym] = {:name => name, :link => link, :icon => icon, :color => color}

  end

  def set_sub_menu(big_menu, sub_menu, name, link=nil)

    link = eval("admin_#{sub_menu}_path") if !link
    @qi_menus[big_menu.to_sym][:elements] = @qi_menus[big_menu.to_sym][:elements] || {}

    @qi_menus[big_menu.to_sym][:elements][sub_menu.to_sym] = {:name => name, :link => link}

  end


  before_action :set_product_display

  before_action :set_locale



  before_action :get_sorting

  def cell_type_from_value(v)
    if v.is_a?(Date)
      :date
    elsif v.is_a?(String)
      :string
    elsif v.is_a?(Time)
      :time
    elsif v.is_a?(TrueClass) || v.is_a?(FalseClass)
      :boolean
    elsif v.to_s =~ /\A[+-]?\d+?\Z/ #numeric
      :integer
    elsif v.to_s =~ /\A[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\Z/ #float
      :float
      # \A(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[0-1]|0[1-9]|[1-2][0-9])
      # T(2[0-3]|[0-1][0-9]):([0-5][0-9]):([0-5][0-9])(\.[0-9]+)?
      # (Z|[+-](?:2[0-3]|[0-1][0-9]):[0-5][0-9])?\Z
    elsif v.to_s =~/\A(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[0-1]|0[1-9]|[1-2][0-9])T(2[0-3]|[0-1][0-9]):([0-5][0-9]):([0-5][0-9])(\.[0-9]+)?(Z|[+-](?:2[0-3]|[0-1][0-9]):[0-5][0-9])?\Z/
      :iso_8601
    else
      :string
    end
  end


  def get_sorting( column_default=nil, direction_default="desc")



    sorting_direction = %w[asc desc].include?(params[:direction]) ? params[:direction] : direction_default
    sorting_column = params[:column] ? params[:column] : column_default

    if sorting_direction and sorting_column
      @sorting = [sorting_column, sorting_direction]
    end
  end


  before_action :set_qi_order

  def set_qi_order
    params[:search] = params[:search] || {}

    session[:qi_sort_string] = session[:qi_sort_string] || {}

    if params[:qi_sort_string].to_s != "" and params[:qi_sort_string][:class]

      if current_admin
        if ap = current_admin.admin_preferences.where(:key => "sort_table_"+params[:qi_sort_string][:class]).first
          ap.value = params[:qi_sort_string][:list].to_s
          ap.save
        else
          current_admin.admin_preferences.create(:key => "sort_table_"+params[:qi_sort_string][:class], :value => params[:qi_sort_string][:list].to_s)
        end



      else
        session[:qi_sort_string][params[:qi_sort_string][:class]] = params[:qi_sort_string][:list].to_s
      end

    else

    end


    if params[:qi_sort_string].to_s != "" and params[:qi_sort_string][:nbr_colonnes].to_s != ""

      if current_admin
        if ap = current_admin.admin_preferences.where(:key => "sort_table_"+params[:qi_sort_string][:class]+"_nbr_col").first
          ap.value = params[:qi_sort_string][:nbr_colonnes].to_s
          ap.save
        else
          current_admin.admin_preferences.create(:key => "sort_table_"+params[:qi_sort_string][:class]+"_nbr_col", :value => params[:qi_sort_string][:nbr_colonnes].to_s)
        end

      else
        session[:qi_sort_string][params[:qi_sort_string][:class]+"_nbr_col"] = params[:qi_sort_string][:nbr_colonnes].to_s
      end

    else

    end




  end


  def sort_by_sorting(var, default=nil)
    if @sorting
      klass = var.klass.to_s

      if eval(klass).valid_sort.include?(@sorting[0])
        if @sorting[0].split(",").size > 0
          order_text = ""
          i = 0
          @sorting[0].split(",").each do |s|

            order_text += "#{s} #{@sorting[1]}"
            order_text += "," if i < (@sorting[0].split(",").size - 1 )
            i+=1
          end
          var = var.order(order_text)
        else
          var = var.order("#{@sorting[0]} #{@sorting[1]}")
        end


      end

    elsif default
      var = var.order(default)
    end



    return var



  end


  def get_public_layout
    "public"


  end


  def set_locale
    # if params[:locale] is nil then I18n.default_locale will be used
    #I18n.locale = params[:locale]#"fr" #

    I18n.locale = params[:lang] || :fr

    @lang = LangSite.find_by_slug I18n.locale.to_s
  end

  def default_url_options(options={})
    { :lang => I18n.locale }  #
  end

  def p_customer_validated
    auth_p_customer()
  end

  def auth_p_customer
    if !current_p_customer
      if @for_order
        redirect_to new_public_p_customer_auth_path(:for_order => true)
      else
        redirect_to new_public_p_customer_auth_path
      end
    end
  end

  def current_p_customer_sheet
    if cookies[:current_p_customer_sheet_id] and p_customer_sheet = PCustomerSheet.where(:id => cookies[:current_p_customer_sheet_id]).first and p_customer_sheet.state == "Panier web"

    else
      p_customer_sheet = PCustomerSheet.new(state: "Panier web")
      p_customer_sheet.price_line_block = PriceLineBlock.new()
      p_customer_sheet.save
      cookies[:current_p_customer_sheet_id] = p_customer_sheet.id



    end

    if current_p_customer and (p_customer_sheet.p_customer_id != current_p_customer.id or p_customer_sheet.price_line_block.p_customer_id != current_p_customer.id)
      p_customer_sheet.p_customer_id = current_p_customer.id
      p_customer_sheet.price_line_block.p_customer_id = current_p_customer.id
      p_customer_sheet.price_line_block.particular_bill = current_p_customer.particular
      p_customer_sheet.price_line_block.particular_send = current_p_customer.particular
      p_customer_sheet.price_line_block.wish_date = Date.today + 3.week
      p_customer_sheet.save



    elsif !current_p_customer and (p_customer_sheet.p_customer_id or p_customer_sheet.price_line_block.p_customer_id)
      p_customer_sheet.p_customer_id = nil
      p_customer_sheet.price_line_block.p_customer_id = nil
      p_customer_sheet.save
    end

    cookies[:current_p_customer_sheet_id] = p_customer_sheet.id

    #raise

    #p_customer_sheet.price_line_block.p_devise_id = cookies[:devise]

    #p_customer_sheet.save

    return p_customer_sheet
  end

    def set_current_p_customer_sheet
      @current_p_customer_sheet = current_p_customer_sheet
    end

    def current_p_customer
      if cookies[:p_customer_auth_token]
        @current_p_customer = PCustomer.where(:online_shop => true).where(:auth_token => cookies[:p_customer_auth_token]).first
      else
        @current_p_customer = nil
      end

      @current_p_customer
    end



    helper_method :super_current_admin, :current_admin, :get_specific_pref, :sort_by_sorting, :current_p_customer, :current_p_customer_sheet





  private


    def auth_admin
      if !current_admin
        redirect_to new_admin_admin_auth_path
      end

    end




    def current_admin

      if cookies[:admin_remember_token]
        if @current_admin = Admin.find_by_remember_token(cookies[:admin_remember_token])
          @current_admin = Admin.find_by_remember_token(cookies[:admin_remember_token])
        else
            cookies[:admin_remember_token] =nil
        end

      end



    end



    def get_specific_pref(key="")

      sp = SpecificPreference.where(:key => key).first

      if sp
        return sp.value
      else
        return ""
      end

    end

    def has_permission?(permission)
     if current_admin and current_admin.has_permission?(permission)
       true
     else
       redirect_to "/admin"

     end
    end

    def is_super_admin
      if current_admin and current_admin.super_admin
        true
      else
        redirect_to "/admin"
      end
    end

    def super_current_admin

      if cookies[:super_admin_remember_token]
        if @super_current_admin = Admin.find_by_remember_token(cookies[:super_admin_remember_token])
          @super_current_admin = Admin.find_by_remember_token(cookies[:super_admin_remember_token])
        else
            cookies[:super_admin_remember_token] =nil
        end

      end



    end

    def set_navbar_dropdown
      @dropdown_elements = [:p_product_cats, :s_brands, :p_product_colors, :p_article_serial_nums, :p_serial_num_types, :p_product_ref_specs, :p_spec_values, :p_grades, :p_product_powers, :p_product_zones]
      @dropdown_title = "Parametrage"
    end

end

