# == Schema Information
#
# Table name: platform_communicates
#
#  id             :integer          not null, primary key
#  title          :string(255)
#  content        :text(65535)
#  tag_field      :text(65535)
#  fake_id        :integer
#  created_at     :datetime         not null
#  updated_at     :datetime         not null
#  order_index    :integer          default("0")
#  watchers_count :integer          default("0")
#  location       :integer          default("0")
#  enroll_field   :string(255)
#  status         :boolean          default("0")
#

class PlatformCommunicate < ApplicationRecord
  enum location: { pc: 0, applet: 1 }
  before_save :add_fake_id, on: [:create, :update]

  has_many :watchers, as: :watchable, dependent: :destroy

  def watched_ext_info(user_id)
    watcher = self.watchers.find_by(user_id: user_id)
    return [] if watcher.blank? or watcher.ext_info.blank?
    str = []
    self.enroll_field.to_s.split(",").each_with_index do |m, index|
      str.push("#{watcher.ext_info["ext#{index + 1}"]}")
    end
    str
  end

  def add_fake_id
    att_ids = []
    if self.url_or_uuid.to_s.include?("http") && self.url_or_uuid.to_s.include?("forumsDetail")
      att_ids += self.url_or_uuid.to_s.scan(/forumsDetail\/\d+/).map { |s| s.match(/\d+/)[0] }
      if att_ids.present?
        self.fake_id = att_ids[0]
      end
    else
      self.fake_id = self.url_or_uuid
    end
  end
end
