# == Schema Information
#
# Table name: topics
#
#  id          :integer          not null, primary key
#  type        :string(255)
#  title       :string(255)
#  uuid        :integer
#  url         :string(255)
#  order_index :integer
#

class Topic < ApplicationRecord

  default_scope { order(order_index: :desc)}

  scope :with_single_type, ->(type){where(type: trans_simpletype_to_classtype(type))}

  def image
    image_url('image')
  end

  def self.trans_simpletype_to_classtype(type)
    case type 
    when 'activity_forum'
      'Topic::ActivityForum'
    when 'banner'
      'Topic::Banner'
    when 'card'
      'Topic::Card'
    when 'cooperator'
      'Topic::Cooperator'
    when 'excellent_project'
      'Topic::ExcellentProject'
    when 'experience_forum'
      'Topic::ExperienceForum'
    when "glcc_news"
      'Topic::GlccNews'
    when 'pinned_forum'
      'Topic::PinnedForum'
    end
  end


  def get_visitor_data
    data = {
      visits: 0,
      created_time: format_time(Time.now),
      from:"other"
    }

    if self.url.include?("gitlink.org.cn/forums/") || self.url.include?("trustie.net/forums/")
      request_memo = Forum::Memos::GetService.call(self.uuid)
      data[:visits] = request_memo.nil? ? 0 : request_memo["memo"]["viewed_count"]
      data[:created_time] = request_memo.nil? ? format_time(Time.now) : request_memo["memo"]["published_time"]
      data[:from] = "forums"  
    end
 
    if self.url.include?("gitlink.org.cn/zone/") || self.url.include?("trustie.net/zone/")
      request_doc = Getway::Cms::GetService.call(self.uuid)
      data[:visits] = request_doc.nil? ? 0 : request_doc["data"]["visits"]
      data[:created_time] = request_doc.nil? ? format_time(Time.now) : request_doc["data"]["publishTime"]  
      data[:from] = "zone"  
    end

    data
  end

  private

  def image_url(type)
      return nil unless Util::FileManage.exists?(self, type)
      Util::FileManage.source_disk_file_url(self, type)
  end

end
