class SettingsController < ApplicationController
  def show
    @old_projects_url = nil
    get_navbar
    get_add_menu
    get_common_menu
    get_personal_menu
    get_third_party
    get_professional_fields
    get_top_system_notification
  end

  private
    def get_navbar 
      @navbar = default_laboratory.navbar
      if User.current.logged?
        pernal_index = {"name"=>"个人主页", "link"=>get_site_url("url", "#{Rails.application.config_for(:configuration)['platform_url']}/current_user"), "hidden"=>false}
        @navbar << pernal_index
      end
    end
    
    def get_add_menu
      @add = []
      Site.add.select(:id, :name, :url, :key).to_a.map(&:serializable_hash).each do |site|
        hash = {}
        site.each {|k, v|
          hash.merge!("#{k}":  get_site_url(k, v))
        }
        @add << hash
      end
    end

    def get_common_menu
      @common = {}
      Site.common.select(:url, :key).each do |site|
        next if site["url"].to_s.include?("current_user") && !User.current.logged?
        @common.merge!("#{site["key"]}": append_http(reset_site_url(site["url"])))
      end
    end

    def get_personal_menu
      @personal = []
      if User.current.logged?
        Site.personal.select(:id, :name, :url, :key).to_a.map(&:serializable_hash).each do |site|
          hash = {}
          site.each {|k, v|
            hash.merge!("#{k}": get_site_url(k, v))
          }
          @personal << hash
        end
      end
    end

    def get_third_party
      return [] if EduSetting.get("is_local") == "true"
      @third_party = []
      @third_party << {
        name: 'GitLink',
        url: GitlinkOauth.oauth_url
      }
      @third_party << {
        name: 'Openkyin',
        url: OpenkylinOauth.oauth_url
      }
    end

    def get_professional_fields
      # @professional_fields = Site.dict

      if Site.dict.count == 0
        "自动化、计算机、机械、材料、航空航天、电子信息、电气、医学、建筑、理学、教育、管理、其他".split("、").each_with_index do |key,index|
          Site.dict.create!(name: key, url: index, key: "professional_field")
        end
      end
      @professional_fields = Site.get_dict_data("professional_field")
    end

    def get_top_system_notification
      @top_system_notification = SystemNotification.is_top.first
    end

    def get_site_url(key, value)
      key.to_s === "url" ? append_http(reset_site_url(value)) : reset_site_url(value)
    end

    def reset_site_url(url)
      return url unless url.to_s.include?("current_user")

      split_arr = url.split('current_user')
      split_arr.length > 1 ? split_arr.join(current_user&.login) : (split_arr << current_user&.login).join('')
    end

    def append_http(url)
      url.to_s.start_with?("http") ? url : [request.protocol, request.host_with_port, url].join('')
    end
end
