<commit_before>require 'miq_bulk_import'
class ConfigurationController < ApplicationController
  logo_dir = File.expand_path(File.join(Rails.root, "public/upload"))
  Dir.mkdir logo_dir unless File.exist?(logo_dir)
  @@logo_file = File.join(logo_dir, "custom_logo.png")

  before_filter :check_privileges
  before_filter :get_session_data
  after_filter :cleanup_action
  after_filter :set_session_data

  def index
    @breadcrumbs = Array.new
    @config_tab = params[:config_tab] ? params[:config_tab] : "ui"
    active_tab = nil
    if role_allows(:feature=>"my_settings_visuals")
      active_tab = 1 if active_tab.nil?
    elsif role_allows(:feature=>"my_settings_default_views")
      active_tab = 2 if active_tab.nil?
    elsif role_allows(:feature=>"my_settings_default_filters")
      active_tab = 3 if active_tab.nil?
    elsif role_allows(:feature=>"my_settings_time_profiles")
      active_tab = 4 if active_tab.nil?
    elsif role_allows(:feature=>"my_settings_my_tags")
      if false
        active_tab = 5 if active_tab.nil?
      end
    end
    @tabform = params[:load_edit_err] ? @tabform : @config_tab + "_#{active_tab}"
    case @config_tab
    when "operations", "ui", "filters"
      if @tabform == "operations_1" || @tabform == "operations_2"
        init_server_options
        @server_options[:server_id] = MiqServer.my_server.id
        @server_options[:remote] = false
      end
      if (@tabform == "filters_1")
       @tabform = @config_tab + "_2"
      end
      if (@tabform == "filters_2")
        @tabform = @config_tab + "_3"
      end
      edit
    when "admin"
      show_users
    end
    render :action=>"show"
  end

  # handle buttons pressed on the button bar
  def button
    @refresh_div = "main_div" # Default div for button.rjs to refresh
    timeprofile_delete if params[:pressed] == "tp_delete"
    copy_record if params[:pressed] == "tp_copy"
    edit_record if params[:pressed] == "tp_edit"

    if ! @refresh_partial && @flash_array == nil # if no button handler ran, show not implemented msg
      add_flash(_("Button not yet implemented"), :error)
      @refresh_partial = "layouts/flash_msg"
      @refresh_div = "flash_msg_div"
    end

    if params[:pressed].ends_with?("_edit") || params[:pressed].ends_with?("_copy")
      render :update do |page|
        page.redirect_to :action=>@refresh_partial, :id=>@redirect_id
      end
    else
      c_buttons, c_xml = build_toolbar_buttons_and_xml(center_toolbar_filename)
      render :update do |page|                    # Use RJS to update the display
        page.replace("flash_msg_div", :partial => "layouts/flash_msg")
        page.replace_html("main_div", :partial => "ui_4") # Replace the main div area contents
        if c_buttons && c_xml
          page << javascript_for_toolbar_reload('center_tb', c_buttons, c_xml)
          page << "$('#center_buttons_div').show();"
        else
          page << "$('#center_buttons_div').hide();"
        end
      end
    end
  end

  def edit
    set_form_vars   # Go fetch the settings into the object for the form
    session[:changed] = @changed = false
    build_tabs
  end

  # New tab was pressed
  def change_tab
    @tabform = @config_tab + "_" + params[:tab] if params[:tab] != "5"
    edit
    render :action=>"show"
  end


  # AJAX driven routine to check for changes in ANY field on the form
  def form_field_changed
    # ui1 edit form
    return unless load_edit("config_edit__ui1","configuration")
    get_form_vars
    @assigned_filters = Array.new
    @changed = (@edit[:new] != @edit[:current])
    render :update do |page|                    # Use JS to update the display
      page.replace(@refresh_div, :partial=>@refresh_partial) if @refresh_div
      page << javascript_for_miq_button_visibility_changed(@changed)
    end
  end

  # AJAX driven routine to check for changes in ANY field on the user form
  def filters_field_changed
    # ui3 form
    return unless load_edit("config_edit__ui3","configuration")
    if params[:all_checked]                         # User checked/unchecked a tree node
      @edit[:show_ids] = params[:all_checked].split(',')
      if !@edit[:show_ids].blank?
        @edit[:new].each_with_index do |arr,i|
          if @edit[:show_ids].include?(arr.id.to_s)
            @edit[:new][i].search_key = nil
          else
            @edit[:new][i].search_key = "_hidden_"
          end
        end
      else      #if everything was unchecked
        @edit[:new].each_with_index do |search,i|
          @edit[:new][i].search_key = nil
        end
      end
    end
    @edit[:current].each_with_index do |arr,i|          #needed to compare each array element's attributes to find out if something has changed
      if @edit[:new][i].search_key != arr.search_key
        @changed = true
        break
      end
    end
    render :update do |page|
      # needed to compare each array element's attributes to find out if something has changed
      @edit[:current].each_with_index do |arr, i|
        id = @edit[:new][i].id
        if @edit[:new][i].search_key != @edit[:current][i].search_key
          style_class = 'cfme-blue-bold-node'
        else
          style_class = 'dynatree-title'
        end
        page << "cfme_dynatree_node_add_class('#{session[:tree_name]}', '#{id}', '#{style_class}')"
      end
      page << javascript_for_miq_button_visibility(@changed) if @changed
    end
  end

  # AJAX driven routine for gtl view selection
  def view_selected
    # ui2 form
    return unless load_edit("config_edit__ui2","configuration")
    @edit[:new][:views][VIEW_RESOURCES[params[:resource]]] = params[:view] # Capture the new view setting
    session[:changed] = (@edit[:new] != @edit[:current])
    @changed = session[:changed]
    render :update do |page|                    # Use JS to update the display
      page.replace 'tab_div', :partial=>"ui_2"
    end
  end

  # AJAX driven routine for theme selection
  def theme_changed
    # ui1 theme changed
    @edit = session[:edit]
    @edit[:new][:display][:theme] = params[:theme]      # Capture the new setting
    session[:changed] = (@edit[:new] != @edit[:current])
    @changed = session[:changed]
    render :update do |page|                    # Use JS to update the display
      page.replace 'tab_div', :partial=>"ui_1"
    end
  end

  # AJAX driven routine for nav style selection
  def nav_style_changed
    @edit = session[:edit]
    @edit[:new][:display][:nav_style] = params[:nav_style]    # Capture the new setting
    session[:changed] = (@edit[:new] != @edit[:current])
    @changed = session[:changed]
    render :update do |page|                    # Use JS to update the display
      page.replace 'tab_div', :partial=>"ui_1"
    end
  end

  # AJAX driven routine for background color selection
  def bg_color_changed
    # ui1 bgcolor changed
    @edit = session[:edit]
    @edit[:new][:display][:bg_color] = params[:bg_color]      # Capture the new setting
    session[:changed] = (@edit[:new] != @edit[:current])
    @changed = session[:changed]
    render :update do |page|                    # Use JS to update the display
      page.replace 'tab_div', :partial=>"ui_1"
    end
  end

  # Assign a tag to a set of objects
  def mytag_create
    if params[:newtags] && params[:newtags].present?     # If user entered tags
      newtags = params[:newtags]
      invalid_chars = newtags.gsub(/[\w\s]/, "")
      if invalid_chars.present?
        invalid_chars = invalid_chars.split(//).uniq.join # Get the unique invalid characters
        msg = "Invalid character".pluralize(invalid_chars.length)
        add_flash(msg + " #{invalid_chars} found in entered tags, only letters, numbers, and underscores are allowed.", :error)
        render :update do |page|
          page.replace("flash_msg_div", :partial => "layouts/flash_msg")
        end
        return
      end
      newtags = params[:newtags].split                      # Put tags in array
      newtags.each do |t|
        Tag.add(t, :cat => session[:userid]) # Add each tag
      end
      session[:mytags] = Tag.all_tags(:cat => session[:userid]).sort      # Get all of the users tags
      render :update do |page|
        page.replace("flash_msg_div", :partial => "layouts/flash_msg")
        page.replace("tab_div", :partial => "configuration/ui_5")
        newtags.each do |tag|
          page << jquery_pulsate_element("mytag#{tag}")
        end
      end
    end
  end

  # Remove a tag from a set of objects
  def mytag_delete
    Tag.remove(params[:tag], :cat => session[:userid])
    session[:mytags] = Tag.all_tags(:cat => session[:userid]).sort      # Get all of the users tags
    render :update do |page|
      page.replace("tab_div", :partial => "ui_5")
    end
  end

  def update
    if params["save"]
      get_form_vars if @tabform != "ui_3"
      case @tabform
      when "ui_1"                                                 # Visual tab
        @settings.merge!(@edit[:new])                                   # Apply the new saved settings

        # Remove any old settings hashes *****************************
        @settings[:display].delete(:pres_mode)                    # :pres_mode replaced by :theme

        db_user = current_user
        unless db_user.nil?                                       # Only if userid is in the DB
          db_user.settings = db_user.settings == nil ? @settings : db_user.settings.merge(@settings)  # Create or merge the settings into the db
          # Remove any old settings hashes *****************************
          db_user.settings[:display].delete(:pres_mode)           # :pres_mode replaced by :theme
          db_user.settings.delete(:css)                           # Moved this to @css
          db_user.settings.delete(:adv_search)                    # These got in around sprint 40 by accident
          db_user.save

          # Now copying ALL display settings into the :css hash so we can easily add new settings
          @settings[:css] ||= Hash.new
          @settings[:css].merge!(@settings[:display])
          @settings[:css].merge!(THEME_CSS_SETTINGS[@settings[:display][:theme]])

          @css ||= Hash.new
          @css.merge!(@settings[:display])
          @css.merge!(THEME_CSS_SETTINGS[@settings[:display][:theme]])
          set_user_time_zone
          add_flash(_("User Interface settings saved for User %s") %  session[:username])
        else
          add_flash(_("User Interface settings saved for this session"))
        end
        edit
        render :action => "show"
        return                                                    # No config file for Visuals yet, just return
      when "ui_2"                                                 # Visual tab
        @settings.merge!(@edit[:new])                                   # Apply the new saved settings

        # Remove any old settings hashes *****************************
        @settings[:display].delete(:pres_mode)                    # :pres_mode replaced by :theme
        @settings[:display].delete(:vmcompare)                    # :vmcompare moved to :views hash
        @settings[:display].delete(:vm_summary_cool)              # :vm_summary_cool moved to :views hash
        @settings[:views].delete(:vm_summary_cool)                # :views/:vm_summary_cool changed to :dashboards
        @settings[:views].delete(:dashboards)                    # :dashboards is obsolete now

        db_user = current_user
        unless db_user.nil?                                       # Only if userid is in the DB
          db_user.settings = db_user.settings == nil ? @settings : db_user.settings.merge(@settings)  # Create or merge the settings into the db
          # Remove any old settings hashes *****************************
          db_user.settings[:display].delete(:pres_mode)           # :pres_mode replaced by :theme
          db_user.settings[:display].delete(:vmcompare)           # :vmcompare moved to :views hash
          db_user.settings[:display].delete(:vm_summary_cool)     # :vm_summary_cool moved to :views hash
          db_user.settings[:views].delete(:vm_summary_cool)       # :views/:vm_summary_cool changed to :dashboards
          db_user.save
          add_flash(_("User Interface settings saved for User %s") %  session[:username])
        else
          add_flash(_("User Interface settings saved for this session"))
        end
        edit
        render :action => "show"
        return                                                      # No config file for Visuals yet, just return
      when "ui_3"                                                   # User Filters tab
        @edit = session[:edit]
        @edit[:current].each do |arr|
          s = MiqSearch.find(arr.id.to_i)
          if @edit[:show_ids]
            if @edit[:show_ids].include?(s.id.to_s)
              s.search_key = nil
            else
              s.search_key = "_hidden_"
            end
            s.save
          end
        end
        add_flash(_("Default Filters saved successfully"))
        edit
        render :action => "show"
        return                                                      # No config file for Visuals yet, just return
      when "ui_4"                                                   # User Filters tab
        @edit = session[:edit]
        @edit[:current].each do |arr|
          s = MiqSearch.find(arr.id.to_i)
          if @edit[:show_ids]
            if @edit[:show_ids].include?(s.id.to_s)
              s.search_key = nil
            else
              s.search_key = "_hidden_"
            end
            s.save
          end
        end
        add_flash(_("Default Filters saved successfully"))
        edit
        render :action => "show"
        return                                                      # No config file for Visuals yet, just return
      when "ui_5"                                                   # My tags, mytag_create method
      end
      @update.config.each_key do |category|
        @update.config[category] = @edit[:new][category].dup
      end
      if @update.validate                                           # Have VMDB class validate the settings
        @update.save                                              # Save other settings for current server
        AuditEvent.success(build_config_audit(@edit[:new], @edit[:current].config))
        add_flash(_("Configuration settings saved"))
        edit
        render :action => "show"
      else
        @update.errors.each do |field,msg|
          add_flash("#{field.titleize}: #{msg}", :error)
        end
        @changed = true
        session[:changed] = @changed
        build_tabs
        render :action => "show"
      end
    elsif params["reset"]
      edit
      add_flash(_("All changes have been reset"), :warning)
      render :action => "show"
    end
  end

  # Show the users list
  def show_timeprofiles
    build_tabs if params[:action] == "change_tab" || ["cancel","add","save"].include?(params[:button])
    if session[:userrole] == "super_administrator" || session[:userrole] == "administrator"
      @timeprofiles = TimeProfile.in_my_region.all(:order => "lower(description) ASC")
    else
      @timeprofiles = TimeProfile.in_my_region.all(:conditions=> ["(profile_type = ? or (profile_type = ? and  profile_key = ?))", "global", "user", session[:userid]], :order => "lower(description) ASC")
    end
    timeprofile_set_days_hours
    drop_breadcrumb( {:name=>"Time Profiles", :url=>"/configuration/change_tab/?tab=4"})
  end

  def timeprofile_set_days_hours(timeprofile=@timeprofile)
    @timeprofile_details = Hash.new
    @timeprofiles.each do |timeprofile|
      @timeprofile_details[timeprofile.description] = Hash.new
      @timeprofile_details[timeprofile.description][:days] = Array.new
      timeprofile.profile[:days].each do |day|
        @timeprofile_details[timeprofile.description][:days].push(
          DateTime::ABBR_DAYNAMES[day.to_i])
      end
      @timeprofile_details[timeprofile.description][:hours] = Array.new
      temp_arr = Array.new
      timeprofile.profile[:hours].each do |h|
        temp_arr.push(h.to_i)
      end
      temp_arr = temp_arr.sort
      st = ""
      temp_arr.each_with_index do |hr,i|
        if hr.to_i+1 == temp_arr[i+1]
          st = "#{get_hr_str(hr).split('-').first}-" if st == ""
        else
          if st != ""
            @timeprofile_details[timeprofile.description][:hours].push(st + get_hr_str(hr).split('-').last)
          else
            @timeprofile_details[timeprofile.description][:hours].push(get_hr_str(hr))
          end
          st = ""
        end
      end
      if @timeprofile_details[timeprofile.description][:hours].length > 1 && @timeprofile_details[timeprofile.description][:hours].first.split('-').first == "12AM" && @timeprofile_details[timeprofile.description][:hours].last.split('-').last == "12AM"      #manipulating midnight hours to be displayed on show screen
        @timeprofile_details[timeprofile.description][:hours][0] = @timeprofile_details[timeprofile.description][:hours].last.split('-').first + '-' + @timeprofile_details[timeprofile.description][:hours].first.split('-').last
        @timeprofile_details[timeprofile.description][:hours].delete_at(@timeprofile_details[timeprofile.description][:hours].length-1)
      end
      @timeprofile_details[timeprofile.description][:tz] = timeprofile.profile[:tz]
    end
  end

  def get_hr_str(hr)
    hours = (1..12).to_a
    hour = hr.to_i
    case hour<commit_msg>Refactor TimeProfile collection (transferred from ManageIQ/manageiq@5dc12831fdb28d38e6c6dd577b98618d651afc66)<commit_after>require 'miq_bulk_import'
class ConfigurationController < ApplicationController
  logo_dir = File.expand_path(File.join(Rails.root, "public/upload"))
  Dir.mkdir logo_dir unless File.exist?(logo_dir)
  @@logo_file = File.join(logo_dir, "custom_logo.png")

  before_filter :check_privileges
  before_filter :get_session_data
  after_filter :cleanup_action
  after_filter :set_session_data

  def index
    @breadcrumbs = Array.new
    @config_tab = params[:config_tab] ? params[:config_tab] : "ui"
    active_tab = nil
    if role_allows(:feature=>"my_settings_visuals")
      active_tab = 1 if active_tab.nil?
    elsif role_allows(:feature=>"my_settings_default_views")
      active_tab = 2 if active_tab.nil?
    elsif role_allows(:feature=>"my_settings_default_filters")
      active_tab = 3 if active_tab.nil?
    elsif role_allows(:feature=>"my_settings_time_profiles")
      active_tab = 4 if active_tab.nil?
    elsif role_allows(:feature=>"my_settings_my_tags")
      if false
        active_tab = 5 if active_tab.nil?
      end
    end
    @tabform = params[:load_edit_err] ? @tabform : @config_tab + "_#{active_tab}"
    case @config_tab
    when "operations", "ui", "filters"
      if @tabform == "operations_1" || @tabform == "operations_2"
        init_server_options
        @server_options[:server_id] = MiqServer.my_server.id
        @server_options[:remote] = false
      end
      if (@tabform == "filters_1")
       @tabform = @config_tab + "_2"
      end
      if (@tabform == "filters_2")
        @tabform = @config_tab + "_3"
      end
      edit
    when "admin"
      show_users
    end
    render :action=>"show"
  end

  # handle buttons pressed on the button bar
  def button
    @refresh_div = "main_div" # Default div for button.rjs to refresh
    timeprofile_delete if params[:pressed] == "tp_delete"
    copy_record if params[:pressed] == "tp_copy"
    edit_record if params[:pressed] == "tp_edit"

    if ! @refresh_partial && @flash_array == nil # if no button handler ran, show not implemented msg
      add_flash(_("Button not yet implemented"), :error)
      @refresh_partial = "layouts/flash_msg"
      @refresh_div = "flash_msg_div"
    end

    if params[:pressed].ends_with?("_edit") || params[:pressed].ends_with?("_copy")
      render :update do |page|
        page.redirect_to :action=>@refresh_partial, :id=>@redirect_id
      end
    else
      c_buttons, c_xml = build_toolbar_buttons_and_xml(center_toolbar_filename)
      render :update do |page|                    # Use RJS to update the display
        page.replace("flash_msg_div", :partial => "layouts/flash_msg")
        page.replace_html("main_div", :partial => "ui_4") # Replace the main div area contents
        if c_buttons && c_xml
          page << javascript_for_toolbar_reload('center_tb', c_buttons, c_xml)
          page << "$('#center_buttons_div').show();"
        else
          page << "$('#center_buttons_div').hide();"
        end
      end
    end
  end

  def edit
    set_form_vars   # Go fetch the settings into the object for the form
    session[:changed] = @changed = false
    build_tabs
  end

  # New tab was pressed
  def change_tab
    @tabform = @config_tab + "_" + params[:tab] if params[:tab] != "5"
    edit
    render :action=>"show"
  end


  # AJAX driven routine to check for changes in ANY field on the form
  def form_field_changed
    # ui1 edit form
    return unless load_edit("config_edit__ui1","configuration")
    get_form_vars
    @assigned_filters = Array.new
    @changed = (@edit[:new] != @edit[:current])
    render :update do |page|                    # Use JS to update the display
      page.replace(@refresh_div, :partial=>@refresh_partial) if @refresh_div
      page << javascript_for_miq_button_visibility_changed(@changed)
    end
  end

  # AJAX driven routine to check for changes in ANY field on the user form
  def filters_field_changed
    # ui3 form
    return unless load_edit("config_edit__ui3","configuration")
    if params[:all_checked]                         # User checked/unchecked a tree node
      @edit[:show_ids] = params[:all_checked].split(',')
      if !@edit[:show_ids].blank?
        @edit[:new].each_with_index do |arr,i|
          if @edit[:show_ids].include?(arr.id.to_s)
            @edit[:new][i].search_key = nil
          else
            @edit[:new][i].search_key = "_hidden_"
          end
        end
      else      #if everything was unchecked
        @edit[:new].each_with_index do |search,i|
          @edit[:new][i].search_key = nil
        end
      end
    end
    @edit[:current].each_with_index do |arr,i|          #needed to compare each array element's attributes to find out if something has changed
      if @edit[:new][i].search_key != arr.search_key
        @changed = true
        break
      end
    end
    render :update do |page|
      # needed to compare each array element's attributes to find out if something has changed
      @edit[:current].each_with_index do |arr, i|
        id = @edit[:new][i].id
        if @edit[:new][i].search_key != @edit[:current][i].search_key
          style_class = 'cfme-blue-bold-node'
        else
          style_class = 'dynatree-title'
        end
        page << "cfme_dynatree_node_add_class('#{session[:tree_name]}', '#{id}', '#{style_class}')"
      end
      page << javascript_for_miq_button_visibility(@changed) if @changed
    end
  end

  # AJAX driven routine for gtl view selection
  def view_selected
    # ui2 form
    return unless load_edit("config_edit__ui2","configuration")
    @edit[:new][:views][VIEW_RESOURCES[params[:resource]]] = params[:view] # Capture the new view setting
    session[:changed] = (@edit[:new] != @edit[:current])
    @changed = session[:changed]
    render :update do |page|                    # Use JS to update the display
      page.replace 'tab_div', :partial=>"ui_2"
    end
  end

  # AJAX driven routine for theme selection
  def theme_changed
    # ui1 theme changed
    @edit = session[:edit]
    @edit[:new][:display][:theme] = params[:theme]      # Capture the new setting
    session[:changed] = (@edit[:new] != @edit[:current])
    @changed = session[:changed]
    render :update do |page|                    # Use JS to update the display
      page.replace 'tab_div', :partial=>"ui_1"
    end
  end

  # AJAX driven routine for nav style selection
  def nav_style_changed
    @edit = session[:edit]
    @edit[:new][:display][:nav_style] = params[:nav_style]    # Capture the new setting
    session[:changed] = (@edit[:new] != @edit[:current])
    @changed = session[:changed]
    render :update do |page|                    # Use JS to update the display
      page.replace 'tab_div', :partial=>"ui_1"
    end
  end

  # AJAX driven routine for background color selection
  def bg_color_changed
    # ui1 bgcolor changed
    @edit = session[:edit]
    @edit[:new][:display][:bg_color] = params[:bg_color]      # Capture the new setting
    session[:changed] = (@edit[:new] != @edit[:current])
    @changed = session[:changed]
    render :update do |page|                    # Use JS to update the display
      page.replace 'tab_div', :partial=>"ui_1"
    end
  end

  # Assign a tag to a set of objects
  def mytag_create
    if params[:newtags] && params[:newtags].present?     # If user entered tags
      newtags = params[:newtags]
      invalid_chars = newtags.gsub(/[\w\s]/, "")
      if invalid_chars.present?
        invalid_chars = invalid_chars.split(//).uniq.join # Get the unique invalid characters
        msg = "Invalid character".pluralize(invalid_chars.length)
        add_flash(msg + " #{invalid_chars} found in entered tags, only letters, numbers, and underscores are allowed.", :error)
        render :update do |page|
          page.replace("flash_msg_div", :partial => "layouts/flash_msg")
        end
        return
      end
      newtags = params[:newtags].split                      # Put tags in array
      newtags.each do |t|
        Tag.add(t, :cat => session[:userid]) # Add each tag
      end
      session[:mytags] = Tag.all_tags(:cat => session[:userid]).sort      # Get all of the users tags
      render :update do |page|
        page.replace("flash_msg_div", :partial => "layouts/flash_msg")
        page.replace("tab_div", :partial => "configuration/ui_5")
        newtags.each do |tag|
          page << jquery_pulsate_element("mytag#{tag}")
        end
      end
    end
  end

  # Remove a tag from a set of objects
  def mytag_delete
    Tag.remove(params[:tag], :cat => session[:userid])
    session[:mytags] = Tag.all_tags(:cat => session[:userid]).sort      # Get all of the users tags
    render :update do |page|
      page.replace("tab_div", :partial => "ui_5")
    end
  end

  def update
    if params["save"]
      get_form_vars if @tabform != "ui_3"
      case @tabform
      when "ui_1"                                                 # Visual tab
        @settings.merge!(@edit[:new])                                   # Apply the new saved settings

        # Remove any old settings hashes *****************************
        @settings[:display].delete(:pres_mode)                    # :pres_mode replaced by :theme

        db_user = current_user
        unless db_user.nil?                                       # Only if userid is in the DB
          db_user.settings = db_user.settings == nil ? @settings : db_user.settings.merge(@settings)  # Create or merge the settings into the db
          # Remove any old settings hashes *****************************
          db_user.settings[:display].delete(:pres_mode)           # :pres_mode replaced by :theme
          db_user.settings.delete(:css)                           # Moved this to @css
          db_user.settings.delete(:adv_search)                    # These got in around sprint 40 by accident
          db_user.save

          # Now copying ALL display settings into the :css hash so we can easily add new settings
          @settings[:css] ||= Hash.new
          @settings[:css].merge!(@settings[:display])
          @settings[:css].merge!(THEME_CSS_SETTINGS[@settings[:display][:theme]])

          @css ||= Hash.new
          @css.merge!(@settings[:display])
          @css.merge!(THEME_CSS_SETTINGS[@settings[:display][:theme]])
          set_user_time_zone
          add_flash(_("User Interface settings saved for User %s") %  session[:username])
        else
          add_flash(_("User Interface settings saved for this session"))
        end
        edit
        render :action => "show"
        return                                                    # No config file for Visuals yet, just return
      when "ui_2"                                                 # Visual tab
        @settings.merge!(@edit[:new])                                   # Apply the new saved settings

        # Remove any old settings hashes *****************************
        @settings[:display].delete(:pres_mode)                    # :pres_mode replaced by :theme
        @settings[:display].delete(:vmcompare)                    # :vmcompare moved to :views hash
        @settings[:display].delete(:vm_summary_cool)              # :vm_summary_cool moved to :views hash
        @settings[:views].delete(:vm_summary_cool)                # :views/:vm_summary_cool changed to :dashboards
        @settings[:views].delete(:dashboards)                    # :dashboards is obsolete now

        db_user = current_user
        unless db_user.nil?                                       # Only if userid is in the DB
          db_user.settings = db_user.settings == nil ? @settings : db_user.settings.merge(@settings)  # Create or merge the settings into the db
          # Remove any old settings hashes *****************************
          db_user.settings[:display].delete(:pres_mode)           # :pres_mode replaced by :theme
          db_user.settings[:display].delete(:vmcompare)           # :vmcompare moved to :views hash
          db_user.settings[:display].delete(:vm_summary_cool)     # :vm_summary_cool moved to :views hash
          db_user.settings[:views].delete(:vm_summary_cool)       # :views/:vm_summary_cool changed to :dashboards
          db_user.save
          add_flash(_("User Interface settings saved for User %s") %  session[:username])
        else
          add_flash(_("User Interface settings saved for this session"))
        end
        edit
        render :action => "show"
        return                                                      # No config file for Visuals yet, just return
      when "ui_3"                                                   # User Filters tab
        @edit = session[:edit]
        @edit[:current].each do |arr|
          s = MiqSearch.find(arr.id.to_i)
          if @edit[:show_ids]
            if @edit[:show_ids].include?(s.id.to_s)
              s.search_key = nil
            else
              s.search_key = "_hidden_"
            end
            s.save
          end
        end
        add_flash(_("Default Filters saved successfully"))
        edit
        render :action => "show"
        return                                                      # No config file for Visuals yet, just return
      when "ui_4"                                                   # User Filters tab
        @edit = session[:edit]
        @edit[:current].each do |arr|
          s = MiqSearch.find(arr.id.to_i)
          if @edit[:show_ids]
            if @edit[:show_ids].include?(s.id.to_s)
              s.search_key = nil
            else
              s.search_key = "_hidden_"
            end
            s.save
          end
        end
        add_flash(_("Default Filters saved successfully"))
        edit
        render :action => "show"
        return                                                      # No config file for Visuals yet, just return
      when "ui_5"                                                   # My tags, mytag_create method
      end
      @update.config.each_key do |category|
        @update.config[category] = @edit[:new][category].dup
      end
      if @update.validate                                           # Have VMDB class validate the settings
        @update.save                                              # Save other settings for current server
        AuditEvent.success(build_config_audit(@edit[:new], @edit[:current].config))
        add_flash(_("Configuration settings saved"))
        edit
        render :action => "show"
      else
        @update.errors.each do |field,msg|
          add_flash("#{field.titleize}: #{msg}", :error)
        end
        @changed = true
        session[:changed] = @changed
        build_tabs
        render :action => "show"
      end
    elsif params["reset"]
      edit
      add_flash(_("All changes have been reset"), :warning)
      render :action => "show"
    end
  end

  # Show the users list
  def show_timeprofiles
    build_tabs if params[:action] == "change_tab" || ["cancel","add","save"].include?(params[:button])
    if session[:userrole] == "super_administrator" || session[:userrole] == "administrator"
      @timeprofiles = TimeProfile.in_my_region.all(:order => "lower(description) ASC")
    else
      @timeprofiles = TimeProfile.in_my_region.all(:conditions=> ["(profile_type = ? or (profile_type = ? and  profile_key = ?))", "global", "user", session[:userid]], :order => "lower(description) ASC")
    end
    timeprofile_set_days_hours
    drop_breadcrumb( {:name=>"Time Profiles", :url=>"/configuration/change_tab/?tab=4"})
  end

  def timeprofile_set_days_hours(timeprofile=@timeprofile)
    @timeprofile_details = Hash.new
    @timeprofiles.each do |timeprofile|
      @timeprofile_details[timeprofile.description] = Hash.new
      @timeprofile_details[timeprofile.description][:days] = 
        timeprofile.profile[:days].collect { |day| DateTime::ABBR_DAYNAMES[day.to_i] }
      @timeprofile_details[timeprofile.description][:hours] = Array.new
      temp_arr = timeprofile.profile[:hours].collect(&:to_i).sort
      st = ""
      temp_arr.each_with_index do |hr,i|
        if hr.to_i+1 == temp_arr[i+1]
          st = "#{get_hr_str(hr).split('-').first}-" if st == ""
        else
          if st != ""
            @timeprofile_details[timeprofile.description][:hours].push(st + get_hr_str(hr).split('-').last)
          else
            @timeprofile_details[timeprofile.description][:hours].push(get_hr_str(hr))
          end
          st = ""
        end
      end
      if @timeprofile_details[timeprofile.description][:hours].length > 1 && @timeprofile_details[timeprofile.description][:hours].first.split('-').first == "12AM" && @timeprofile_details[timeprofile.description][:hours].last.split('-').last == "12AM"      #manipulating midnight hours to be displayed on show screen
        @timeprofile_details[timeprofile.description][:hours][0] = @timeprofile_details[timeprofile.description][:hours].last.split('-').first + '-' + @timeprofile_details[timeprofile.description][:hours].first.split('-').last
        @timeprofile_details[timeprofile.description][:hours].delete_at(@timeprofile_details[timeprofile.description][:hours].length-1)
      end
      @timeprofile_details[timeprofile.description][:tz] = timeprofile.profile[:tz]
    end
  end

  def get_hr_str(hr)
    hours = (1..12).to_a
    hour = hr.to_i
    case hour
{'fraction_non_alphanumeric': 0.11886194189733482, 'fraction_numerical': 0.003456451566829491, 'mean_word_length': 2.3648596693579393, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 77, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 8}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 56, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3389528', 'n_tokens_mistral': 10117, 'n_tokens_neox': 9886, 'n_words': 2481}