class MembersController < ApplicationController
  helper_method :current_user
  include AttributeValuesHelper
  def index
    page_roles = OrbitHelper.page_categories
    page_role_status = OrbitHelper.page_role_status
    params = OrbitHelper.params
    page = Page.where(:page_id => params[:page_id]).first rescue nil
    fields_to_show = page.custom_array_field if !page.nil? rescue []
    fields_to_show = [
                        {"key"=>"name", "type"=>"profile","sort_order"=>2,"link_to_show"=>true},
                        {"key"=>"email", "type"=>"profile"},
                        {"key"=>"office_tel", "type"=>"profile"}
                     ] if fields_to_show.blank?

    member_sort_position = OrbitHelper.member_sort_position
    sort = nil
    if !member_sort_position
      sort_select = fields_to_show.to_enum.with_index.select{|v| v[0]['key']=='name'}
      sort = sort_select.blank? ? nil : sort_select[0][1]
    end
    if page_roles.include?("all")
      roles = Role.all.asc(:key).collect do |role|
        { "title" => role.title, "id" => role.id }
      end
    else
      page_role_status.each do |status_id|
        page_roles << (RoleStatus.find(status_id).role.id.to_s rescue '')
      end
      roles = Role.where(:id.in => page_roles.uniq).asc(:key).collect do |role|
        { "title" => role.title, "id" => role.id, "status" => RoleStatus.where(:role_id=>role, :_id.in=>page_role_status).asc(:key).to_a }
      end
    end
    tag = nil
    role_list = []
    roles.each do |role|
      status_list = []
      if !role['status'].blank?
        role['status'].each do |status|
          member_profiles = get_members_by_status(status, sort, fields_to_show, member_sort_position, params)
          status_list << { "status-title" => status.title, "members" => member_profiles } if !member_profiles.blank?
        end
      else
        # Members with status
        role_status = RoleStatus.order_by(:key=>"asc").where(:role_id=>role['id'])
        role_status_ids = role_status.collect{|status| status.id.to_s}

        role_status.each do |status|
          member_profiles = get_members_by_status(status, sort, fields_to_show, member_sort_position, params)
          next if member_profiles.blank?
          status_list << { "status-title" => status.title, "members" => member_profiles }
        end

        # Members without status
        member_profiles = []

        if params[:tag].blank?
          MemberProfile.not_in(:role_status_ids.in=>role_status_ids).where(:role_ids.in=>[role['id']]).collect do |profile|
            if profile.user.nil? || profile.user.approved
              get_member_data_return = get_member_data(profile, fields_to_show)
              if !get_member_data_return.nil?
                member_profiles << get_member_data_return
              end
            end
          end
        else
          tag = MemberTag.find(params[:tag]) rescue nil
          if !tag.nil?
            MemberProfile.not_in(:role_status_ids.in=>role_status_ids).where(:role_ids.in=>[role['id']], :member_tag_ids.in => [tag.id]).each do |profile|
              if profile.user.nil? || profile.user.approved
                get_member_data_return = get_member_data(profile, fields_to_show)
                if !get_member_data_return.nil?
                  member_profiles << get_member_data_return
                end
              end
            end 
          end
        end
        if member_sort_position
          member_profiles = member_profiles.sort_by{|data| (data['list_order'])} rescue member_profiles
        else
          member_profiles = member_profiles.sort_by{|data| (data['profile_data'][sort]['sort_value'] rescue 0)} rescue member_profiles
        end
        status_list << { "status-title" => role['title'], "members" => member_profiles } if !member_profiles.blank?
      end
      role_list << {  "role-title" => role['title'], "status-list" => status_list }
    end
    {
      "roles" => role_list,
      "extras" => {
        "widget-title"=>((params[:tag].blank? ? t(:member_) : (tag.nil? ? "Tag not found" : t(:member_) + " - Filtered by <i>#{tag.title}</i>")) rescue t(:member_))
      }
    }
  end

  def get_members_by_status(status, sort=nil, fields_to_show, member_sort_position, params)
    member_profiles = []
    mps = []
    if params[:tag].blank?
      mps = status.member_profiles.asc(:first_name)
    else
      tag = MemberTag.find(params[:tag]) rescue nil
      mps = status.member_profiles.where(:member_tag_ids.in => [tag.id]).asc(:first_name)  if !tag.nil?
    end
    
    mps.each do |member|
      if member.user.nil? || member.user.approved
        get_member_data_return = get_member_data(member, fields_to_show)
        if !get_member_data_return.nil?
          member_profiles << get_member_data_return
        end
      end
    end
    if member_sort_position
      return member_profiles.sort_by{|data| (data['list_order'])} rescue member_profiles
    else
      return member_profiles.sort_by{|data| (data['profile_data'][sort]['sort_value'] rescue 0)} rescue member_profiles
    end
  end

  def get_member_data(member, fields_to_show)
    image = member.avatar.present? ? member.avatar.thumb.url : ActionController::Base.helpers.asset_path('member-pic.png')
    member_data_return = member_data(member, fields_to_show)
    if !member_data_return.blank?
      {
        'profile_data'=> member_data_return, 
        'list_order' => member.position,
        'name' => member.name,
        'image'=>image, 
        "link_to_show" => OrbitHelper.url_to_show(member.to_param)
      }
    else
      nil
    end
  end

  def show
    params = OrbitHelper.params
    member = MemberProfile.find_by(uid: params[:uid]) rescue nil
    page = Page.where(:page_id => params[:page_id]).first rescue nil

    profile_data = []
    fields_to_show = []

    fields_to_show = page.custom_array_field_for_show rescue []

    #role status
    member.roles.where(:disabled => false).asc("_id").collect do |role|
      role_status = member.role_statuses.where(role_id: role.id).map{|t|t.title.to_s}.join(',') rescue ''
      profile_data = profile_data.push({"key"=>"role_status", "title"=>"", "value"=> role_status, "title_class"=>"member-data-title-role-status", "value_class"=>"member-data-value-role-status"}) if !role_status.blank?
      if fields_to_show.blank?
        attribute_field = role.attribute_fields.first
        if !attribute_field.blank? && !attribute_field.to_show.blank?
          profile_data = profile_data + member_data(member, [{"id"=> attribute_field.id.to_s, "key"=> attribute_field.key.to_s, "type"=>"role"}])
        end
      end
    end
    if fields_to_show.blank?
      fields_to_show = [
                        {"key"=>"name", "type"=>"profile"},
                        {"key"=>"office_tel", "type"=>"profile"},
                        {"key"=>"email", "type"=>"profile"}
                     ] 

      profile_data = profile_data + member_data(member, fields_to_show)

      profile_fields_to_show = []

      # member info
      infos = MemberInfo.order('created_at DESC')
      infos.each do |info|
        info.member_profile_fields.each do |member_profile_field|
          profile_fields_to_show << {"id"=> member_profile_field.id.to_s, "key"=> member_profile_field.key, "type"=>"custom"} if !member_profile_field.to_show.blank?
        end
      end
      profile_data = profile_data + member_data(member, profile_fields_to_show)

      # member role
      role_fields_to_show = []
      member.roles.where(:disabled => false).asc("_id").collect do |role| 
        role.attribute_fields.where(:key.ne => 'job_title').asc("_id").each do |attribute_field|
          role_fields_to_show << {"id"=> attribute_field.id.to_s,"key"=> attribute_field.key.to_s, "type"=>"role"} if !attribute_field.to_show.blank?
        end
      end
      profile_data = profile_data + member_data(member, role_fields_to_show)
    else
      profile_data = profile_data + member_data(member, fields_to_show)
      auto = profile_data.select{|pd| pd if pd["key"] == "autobiography"}
      if !auto.blank?
        auto = auto.first
        profile_data.delete(auto)
      end
    end

    # member plugin
    # plugins = (current_site.personal_plugins_sort.blank? ? OrbitApp::Plugin::Registration.all : OrbitApp::Plugin::Registration.sort_by_array(current_site.personal_plugins_sort)) rescue nil
    if current_site.personal_plugins_sort.blank?
        plugins = OrbitApp::Plugin::Registration.all rescue nil
    else
        plugin_list = OrbitApp::Plugin::Registration.all.collect{|p| p.module_app_name}
        plugin_list = current_site.personal_plugins_sort | plugin_list
        plugins = OrbitApp::Plugin::Registration.sort_by_array(plugin_list) rescue nil
    end
    plugin_list = plugins.collect.with_index do |plugin, idx|

      intro = PersonalPluginIntro.find_by(member_profile_id: member.id, _type: "#{plugin.app_name}Intro") rescue nil

      if intro.nil? or intro.complete_list

        plugin_data = plugin.app_name.constantize.where(member_profile_id: member,:is_hidden=>false) rescue nil
        # pd = plugin_data.collect do |p|
        #   slug_title = ["JournalPaper","WritingConference"].include?(plugin.app_name) ? p.create_link : p.slug_title
        #   {
        #     "data_title" => slug_title,
        #     "link_to_show" => OrbitHelper.url_to_plugin_show(p.to_param,plugin.module_app_name.underscore)
        #   }
        # end
        pd = []
        has_plugin_method = plugin.app_name.constantize.respond_to?("get_plugin_datas_to_member") rescue false

        if !has_plugin_method && (plugin.app_name == 'JournalPaper' or plugin.app_name == 'WritingConference' or plugin.app_name == 'Book')

          pd_title = {}

          temp_pds = plugin_data.sort_for_frontend rescue nil 
          temp_pds = plugin_data.where(:is_hidden=>false).desc(:year) if temp_pds.nil? # for old sites without plugins update

          plugin_datas = temp_pds.collect do |p|
            {
              "pd_datas" => [{ "data_title" => "<a href='#{OrbitHelper.url_to_plugin_show(p.to_param,plugin.module_app_name.underscore)}' title='#{p.create_link}' target='_blank'>#{p.create_link}" }]
            }
          end

        else
          
          datas = plugin.app_name.constantize.get_plugin_datas_to_member(plugin_data)
          pd_title = datas[0] rescue {}
          plugin_datas = datas[1] rescue {}

        end

      end

      if !intro.blank?

        if !intro.brief_intro.blank?
          pdi = []
          pdi << {"data_intro_title" => intro.text.html_safe}
        end

        if intro.complete_list.blank?
          complete_display = "hide"

          pd_title = {}
          plugin_datas = {}
        end

        if intro.brief_intro.blank?
          brief_display = "hide"
          pdi = {}
        end
      else

        pdi = [{"data_intro_title" => ''}] if !plugin_datas.blank?

      end


      {
        "plugin_data" => pd,
        "pd_title" => pd_title,
        "plugin_datas" => plugin_datas,
        "plugin_data_intro" => pdi,
        "complete_display" => complete_display,
        "brief_display" => brief_display,
        "plugin_name" => plugin.module_app_name.underscore,
        "plugin_title" => t('module_name.'+plugin.module_app_name.underscore),
        "plugin_class" => idx==0 ? "active" : ""
      }  

    end 
    plugin_list = plugin_list.reject{|plugin| plugin['plugin_datas'].blank? and plugin['plugin_data_intro'].blank?}

    vlog_module = ModuleApp.find_by_key("vlog") rescue nil

    if !vlog_module.nil? && !member.user.nil?
      plugin_data = VLog.where(create_user_id: member.user.id) rescue nil
      if plugin_data.count > 0
        datas = VLog.get_plugin_datas_to_member(plugin_data)
        pd_title = datas[0] rescue {}
        plugin_datas = datas[1] rescue {}

        plugin_list << {
          "plugin_data" => [],
          "pd_title" => pd_title,
          "plugin_datas" => plugin_datas,
          "plugin_data_intro" => {},
          "complete_display" => nil,
          "brief_display" => nil,
          "plugin_name" => vlog_module.get_registration.key,
          "plugin_title" => t("vlog.vlog"),
          "plugin_class" => ""
        }
      end
    end

    if !auto.blank?
      if plugin_list.empty?
        plugin_list << {"plugin_data"=>[], "pd_title"=>[{"plugin_data_title"=>auto["title"]}], "plugin_datas"=>[{"pd_datas"=>[{"data_title"=>auto["value"]}]}], "plugin_name" => auto["key"],"plugin_class" => "active", "plugin_title" => auto["title"], "plugin_data_intro"=>[{"data_intro_title"=>""}], "complete_display"=>nil, "brief_display"=>nil}
      else
        plugin_list.first["plugin_class"] = ""
        plugin_list.unshift({"plugin_data"=>[], "pd_title"=>[{"plugin_data_title"=>auto["title"]}], "plugin_datas"=>[{"pd_datas"=>[{"data_title"=>auto["value"]}]}], "plugin_name" => auto["key"],"plugin_class" => "active", "plugin_title" => auto["title"], "plugin_data_intro"=>[{"data_intro_title"=>""}], "complete_display"=>nil, "brief_display"=>nil})
      end
    end 
    
    {
      "plugins" => plugin_list,
      "profile_data" => profile_data,
      "data" => {
        "image" => member.avatar.present? ? member.avatar.url : ActionController::Base.helpers.asset_path('member-pic.png'),
        "name" => member.name
      }
    }
  end

  def member_data(member, fields_to_show)
    profile_data = []
    fields_to_show.each do |field|
    privacy_approved_status = true
    if field['type'] != 'role'
    field_key = field["key"]
    else
    field_key = field["id"]
    end
    privacy_approved_status = false if member.get_privacy_type_for_field(field_key) != "public"
    if !OrbitHelper.current_user.nil?
      if(member.get_privacy_type_for_field(field_key) == "logged_in")
        privacy_approved_status = true
      elsif(member.get_privacy_type_for_field(field_key) == "locked")
        if member.user.id == OrbitHelper.current_user.id || OrbitHelper.current_user.is_admin?
          privacy_approved_status = true
        end
      end
    end
    if member.get_privacy_type_for_field(field_key) == "default"
      if field['type'] != 'role'
        privacy_approved_status = true #Todo: set not role field's default privacy_approved_status
      else
        case (AttributeField.find(field["id"]).privacy_default rescue nil)
        when 'public'
          privacy_approved_status = true
        when 'logged_in'
          privacy_approved_status = true if !OrbitHelper.current_user.nil?
        when 'locked'
          if !OrbitHelper.current_user.nil?
            privacy_approved_status = true if member.user.id == OrbitHelper.current_user.id || OrbitHelper.current_user.is_admin?
          end
        end
      end
    end
    case field['type']
    when 'profile'
      next if !privacy_approved_status
      field_data = member.get_attribute_data(field) rescue {}
    when 'custom'
      if !field['id'].blank?
        next if !privacy_approved_status
        field_data = member.member_profile_field_values.find_by(:member_profile_field_id=>field['id'],:key=>field['key']).get_field_value rescue {"value" => "&nbsp;"}
      else
        field_data = member.member_profile_field_values.find_by(:key=>field['key']).get_field_value rescue {"value" => "&nbsp;"}
      end
    when 'role'
      av = member.attribute_values.find_by(:attribute_field_id=>field['id']) rescue nil #some role's key has been changed to sort number,so it doesn't work when searching field from using its key 
      field_data = {"value" => "&nbsp;"}
      if !av.nil?
        next if !privacy_approved_status
        r = av.attribute_field.role rescue nil
        if !r.nil?
          if member.roles.include?(r)
            field_data = av.get_field_value(member) rescue {"value" => "&nbsp;"}
          end
        end
      else
        avs = member.attribute_values.find_by(:key=>field['key']) rescue []
        avs.each do |av|
          if !av.nil?
            r = av.attribute_field.role rescue nil
            if !r.nil? && member.roles.include?(r)
              field_data = av.get_field_value(member) rescue {"value" => "&nbsp;"}
              break
            end
          end
        end
        if avs.blank? && !field['id'].nil?
          attr_field = AttributeField.find(field['id']) rescue nil
          if !attr_field.blank? && attr_field.markup.eql?("member_relationship")
            field_data = {
              "key" => attr_field.key,
              "title" => attr_field.title,
              "value" => get_member_show(attr_field.get_member_relationship(member.id.to_s))
            }
            if field_data['value'].blank?
              field_data['value'] = '&nbsp;'
            end
          end
        end
      end
      end
      next if field_data.blank? || field_data['value'].blank? || (OrbitHelper.params[:target_action] == "show" && field_data['value'] == "&nbsp;")
      
      if field['sort_order']
        field_data['sort_value'] = field_data['val'].blank? ? field_data['value'] : field_data['val']
        if !field_data['sort_value'].is_a?(Hash)
          if field_data['sort_value'].is_a?(Integer) || (field_data['sort_value'].is_i? rescue false)
             field_data['sort_value'] = field_data['sort_value'].to_i rescue field_data['sort_value']
          elsif I18n.locale == :zh_tw
            field_data['sort_value'] = field_data['sort_value'].strip.encode("Big5") rescue "簡".encode("Big5")
          end
        end
      end
      @current_field_value = field_data['value']
      if (@current_field_value.gsub('&nbsp;','').strip rescue nil) == ""
        @locale = I18n.locale
        @site_in_use_locales = current_site.in_use_locales
        @new_field_data = Hash.new
        @site_in_use_locales.each_with_index do |locale,i|
        I18n.locale = locale
        @new_field_data = member.get_attribute_data(field) rescue {}
        break if @new_field_data['value'].to_s.gsub('&nbsp;','').strip !=""
      end
      field_data['value'] = @new_field_data['value'].nil? ? "&nbsp" : @new_field_data['value']
      I18n.locale = @locale
      end
      if field['link_to_show']
        if field_data['value'] == '&nbsp;' #空白欄位
          field_data['value'] = "" #若無網站連結，刪除實驗室網站字樣
          field_data['title'] = "" #無網站連結，則不顯示
        elsif field_data['value'].include? 'href='
          field_data['value'] = "<a title='#{field_data['title']}'#{field_data['value']}</a>"
        else
          field_data['value'] = "<a title='#{field_data['value']}' href='#{OrbitHelper.url_to_show(member.to_param)}'>#{field_data['value']}</a>"
        end
        #field_data['value'] = "<a title='#{field_data['value']}' href='#{OrbitHelper.url_to_show(member.to_param)}'>#{field_data['value']}</a>"          
      end

      if field['max_length']
        field_data['value'] = (field_data['value'].length > field['max_length']) ? field_data['value'][0..field['max_length']]+'...' : field_data['value']
      end

      field_data['title_class'] = "member-data-title-"+field['key'].to_s.underscore.gsub('_','-')
      field_data['value_class'] = "member-data-value-"+field['key'].to_s.underscore.gsub('_','-')
      if !field_data['title'].blank? && !field_data['value'].blank?
        profile_data.push(field_data)
      end
    end
    return profile_data
  end
end
