class MembersController < ApplicationController
  helper_method :current_user
  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 = "data['list_order']"
    # else
      # sort = fields_to_show
      #           .collect.with_index{|field,idx| {'sort_order'=>field['sort_order'], 'index'=>idx}}
      #           .select{|field|!field['sort_order'].blank?}
      #           .sort_by{|field|field['sort_order']}
      #           .collect.with_index{|field| "data['profile_data'][#{field['index']}]['sort_value'] rescue 0"}
      # # sort = "[(data['first_name'][0])]"
      # sort = '[('+sort.join('),(')+')]'
      fields_to_show.each_with_index do |field, idx|
        if field["key"] == "name"
          # sort = "[(data['profile_data'][idx]['sort_value'] rescue 0)]"
          sort = idx
        end
      end
    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
      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?
              member_profiles << get_member_data(profile, fields_to_show)
            elsif profile.user.approved
              member_profiles << get_member_data(profile, fields_to_show)
            end
          end
        else
          tag = MemberTag.find(params[:tag]) rescue nil
          MemberProfile.not_in(:role_status_ids.in=>role_status_ids).where(:role_ids.in=>[role['id']], :member_tag_ids.in => [tag.id]).collect do |profile|
            if profile.user.nil?
              member_profiles << get_member_data(profile, fields_to_show)
            elsif profile.user.approved
              member_profiles << get_member_data(profile, fields_to_show)
            end
          end if !tag.nil?
        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 #{tag.title}")) 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_profiles << get_member_data(member, fields_to_show)
      elsif member.user.approved
        member_profiles << get_member_data(member, fields_to_show)
      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')
    {
      'profile_data'=>member_data(member, fields_to_show), 
      'list_order' => member.position,
      'name' => member.name,
      'image'=>image, 
      "link_to_show" => OrbitHelper.url_to_show(member.to_param)
    }
  end
  def show
    params = OrbitHelper.params
    member = MemberProfile.find_by(uid: params[:uid])
    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.where(:key => 'job_title').first
        profile_data = profile_data + member_data(member, [{"id"=> attribute_field.id.to_s, "key"=> attribute_field.key, "type"=>"role"}]) if !attribute_field.blank? and !attribute_field.to_show.blank?
      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, "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" => "#{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
			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" => " "}
        else
          field_data = member.member_profile_field_values.find_by(:key=>field['key']).get_field_value rescue {"value" => " "}
        end
      when 'role'
        if !field['id'].blank?
          next if !privacy_approved_status
          av = member.attribute_values.find_by(:attribute_field_id=>field['id'],:key=>field['key']) rescue nil
          field_data = {"value" => " "}
          if !av.nil?
            r = av.attribute_field.role rescue nil
            if !r.nil?
              if member.roles.include?(r)
                field_data = av.get_field_value rescue {"value" => " "}
              else
                field_data = {"value" => " "}
              end
            else
              field_data = {"value" => " "}
            end
          else
            field_data = {"value" => " "}
          end
        else
          avs = member.attribute_values.where(:key=>field['key']) rescue nil
          field_data = {"value" => " "}
          avs.each do |av|
            if !av.nil?
              r = av.attribute_field.role rescue nil
              if !r.nil?
                if member.roles.include?(r)
                  field_data = av.get_field_value rescue {"value" => " "}
                  break
                else
                  field_data = {"value" => " "}
                end
              else
                field_data = {"value" => " "}
              end
            else
              field_data = {"value" => " "}
            end
          end
        end
      end
      next if field_data.blank? or field_data['value'].blank? or (OrbitHelper.params[:target_action] == "show" && field_data['value'] == " ")
      
      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']
           else
            if I18n.locale == :zh_tw
             field_data['sort_value'] = field_data['sort_value'].strip.encode("Big5") rescue "簡".encode("Big5")
           end
          end
        end
      end
	  @current_field_value = field_data['value']
	  if (@current_field_value.gsub(' ','').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(' ','').strip !=""
		end
		field_data['value'] = @new_field_data['value'].nil? ? " " :@new_field_data['value']
		I18n.locale = @locale
	  end
      if field['link_to_show']
		if field_data['value'] == ' ' #需jquery刪除空白欄位
          field_data['value'] = "" #若無網站連結,刪除實驗室網站字樣
          field_data['title'] = "" #無網站連結,則不顯示
        elsif field_data['value'].include? 'href='
          field_data['value'] = ""
        else
          field_data['value'] = "#{field_data['value']}"
        end
        #field_data['value'] = "#{field_data['value']}"          
      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'].underscore.gsub('_','-')
      field_data['value_class'] = "member-data-value-"+field['key'].underscore.gsub('_','-')
	  next if field_data['value'] == "" || field_data['value'] == ' '
	  profile_data.push(field_data)
    end
    return profile_data
  end
end