class MemberProfile < ApplicationController
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Attributes::Dynamic
  include Mongoid::Tree
  include Mongoid::Tree::Ordering

  include OrbitModel::Status
  include MemberSlug

  field :first_name, type: String, localize: true
  field :last_name, type: String, localize: true
  field :sex
  field :sid
  field :office_tel
  field :birthday, type: Date
  field :address, type: String, localize: true
  field :personal_website
  field :fax, type: String, localize: true
  field :mobile_no, type: String, localize: true
  field :autobiography, type: String, localize: true
  field :email, type: String
  field :position, type: Integer
  field :rss2_id
  field :public_privacy, type: Array, default: []
  field :logged_in_privacy, type: Array, default: []
  field :locked_privacy, type: Array, default: []

  VALID_EMAIL_FORMAT = /\A[^@\s]+@([^@.\s]+\.)+[^@.\s]+\z/
  validates :email, uniqueness: true, format: { with: VALID_EMAIL_FORMAT }, if: :email_present?
  validates :position, uniqueness: true

  has_one :user
  has_and_belongs_to_many :roles
  has_and_belongs_to_many :role_statuses
  has_and_belongs_to_many :member_tags

  has_many :member_profile_field_values
  accepts_nested_attributes_for :member_profile_field_values, allow_destroy: true

  has_many :attribute_values
  accepts_nested_attributes_for :attribute_values, allow_destroy: true

  has_many :personal_plugin_intros

  scope :can_display, ->{where(is_hidden: false).order_by([:is_top,:desc],[:created_at,:desc])}
  before_save :assign_default_position, :if => :assign_default_position?

  before_destroy :delete_personal_plugin_data

  mount_uploader :avatar, AvatarUploader
  # paginates_per 10

  def get_avatar
    avatar = (self.avatar.thumb.url == "thumb_person.png" ? "/assets/thumb_person.png" : self.avatar.thumb.url rescue "/assets/thumb_person.png")
    avatar
  end

  def name
    if self.first_name != "" || self.last_name != ""
      I18n.locale.eql?(:zh_tw) ? "#{self.last_name} #{self.first_name}" : "#{self.first_name} #{self.last_name}"
	else
		@locale = I18n.locale
		@site_in_use_locales = current_site.in_use_locales
		@name = ""
		@site_in_use_locales.each_with_index do |locale,i|
			I18n.locale = locale
			@name = (I18n.locale.eql?(:zh_tw) ? "#{self.last_name} #{self.first_name}" : "#{self.first_name} #{self.last_name}")
			@name = @name.gsub('&nbsp;','').strip
			break if @name !=""
		end
		I18n.locale = @locale
		return @name
	end 
  end

  def get_privacy_type_for_field(id)
    status = nil
    if self.public_privacy.include?(id)
      status = "public"
    elsif self.logged_in_privacy.include?(id)
      status = "logged_in"
    elsif self.locked_privacy.include?(id)
      status = "locked"
    else
      status = "public"
    end
    status
  end

  def name_translations
    {
      "en" => "#{self.first_name_translations["en"]}  #{self.last_name_translations["zh_tw"]}",
      "zh_tw" => "#{self.last_name_translations["zh_tw"]} #{self.first_name_translations["zh_tw"]}"
    }
  end

  def disable_role=(var)
    var[:id].each do |id,val|  
      if (val=="true")
        self.role_ids.reject!{|t| t.to_s == id}
      elsif(val=="false")
        self.role_ids += Array(id)
      end
    end
  end

  def new_attribute_values=(fields,attribute_type=nil)
    fields.each do |key,field|
      if attribute_type.eql?("role")
        self.attribute_values.build(field)
      else
        self.member_profile_field_values.build(field)
      end
    end
  end

  def get_attribute_value(attribute_field,attribute_type=nil)
    if attribute_type.eql?("role")
      AttributeValue.find_by(attribute_field_id: attribute_field.id, member_profile_id: self.id)
    else
      MemberProfileFieldValue.find_by(member_profile_field_id: attribute_field.id, member_profile_id: self.id)
    end
  end

  def get_attribute_values(attribute_type=nil)
    if attribute_type.eql?("role")
      @attribute_values = self.attribute_values rescue nil
    else
      @attribute_values = self.member_profile_field_values rescue nil
    end
  end
  
  def get_value_from_field_id(field_id,attribute_type=nil)
    if attribute_type.eql?("role")
      values = get_attribute_values(attribute_type)
      value = values.detect {|value| value.attribute_field_id == field_id} rescue nil
      value ? value : nil
    else
      values = get_attribute_values
      value = values.detect {|value| value.member_profile_field_id == field_id} rescue nil
      value ? value : nil
    end
  end

  def self.get_member_list_attribute_field(field_key, attribute_type=nil)
    if attribute_type.eql?("role")
      AttributeField.find_by(key: field_key)
   else
     MemberProfileField.find_by(key: field_key)    
   end
  end

  def self.get_member_list_attribute_value(member_profile_id,field_id,attribute_type=nil)
    if attribute_type.eql?("role")
      AttributeValue.find_by(member_profile_id: member_profile_id, attribute_field_id: field_id)
    else
      MemberProfileFieldValue.find_by(member_profile_id: member_profile_id, member_profile_field_id: field_id)
    end
  end

  def self.get_role_member_data_by_sort(field_key, role_status_id)
    a = Array.new
    attribute_field_data = get_member_list_attribute_field(field_key,"role")
    self.where(role_status_ids: role_status_id).desc(:_id).collect{|t| a << [ get_member_list_attribute_value(t.id,attribute_field_data.id)['val'].to_i, t ]  }
    member_data = a.sort
    member_data_tmp = member_data.collect {|v| v[1] }
  end

  def get_attribute_data(field)
    if field["key"] == "member_tags"
      params = OrbitHelper.params
      data = self.send(field["key"]).collect{|tag| "<span class='label label-info'><a title='#{tag.title}' style='color:#fff;' href='/#{I18n.locale.to_s}#{params["url"]}/?tag=#{tag.id.to_s}'>#{tag.title}</a></span>&nbsp;"}.join("")
    else
      data = self.send(field["key"]) rescue ""
    end
    data = (data =~ /\A#{URI::regexp(['http', 'https'])}\z/) ? "<a href='#{data}' target='blank'>#{data}</a>" : data
    data = (data =~ /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i) ? "<a href='mailto:#{data}' title='#{data}'>#{data}</a>" : data
    field_data = data.blank? ? {"key" => field["key"],"title" => I18n.t("users."+field["key"]), "value" => "&nbsp;"} : {"key" => field["key"],"title" => I18n.t("users."+field["key"]), "value" =>data}
    field_data
  end

  def get_image_for_show
    if self.avatar.present? 
      image = self.avatar.thumb.url
    else
      image = "http://placehold.it/100x100"
    end

    image_fields = {"img_src" => image}
  end

  def delete_personal_plugin_data
    OrbitApp::Plugin::Registration.all.each do |plugin|
      class_name = plugin.app_name.constantize
      plugin_data = class_name.where(member_profile_id: self.id)
      plugin_data.delete
    end 
  end

  def assign_default_position?
    self.position.nil? || self.parent_id_changed?
  end

  def email_present?
    self.email.present?
  end

  def get_role_statuses(role_id)
    RoleStatus.where(role_id: role_id).any_of(member_profile_ids: self.id)
  end
end
