# frozen_string_literal: true

require_relative 'user'

module Mixi2
  class Post < Diva::Model
    include Diva::Model::MessageMixin

    register :mixi2_post, name: 'mixi2 ポスト', timeline: true

    field.has :user, Mixi2::User, required: true
    field.string :title, required: true
    field.string :description, required: true
    field.uri :uri, required: true
    field.time :created, required: true

    POST_URI_REGEXP = %r!\Ahttps://mixi.social/@(?<screen_name>[A-Za-z0-9_]+)/posts/(?<post_uuid>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\z!

    handle POST_URI_REGEXP do |uri|
      uri = Diva::URI(uri)
      m = POST_URI_REGEXP.match(uri.to_s)
      Delayer::Deferred.when(
        [
          Thread.new { Nokogiri::HTML(uri.to_uri.open(&:read)) },
          Delayer.Deferred.new { Mixi2::User.find_by_uri("https://mixi.social/@#{m['screen_name']}") }
        ]
      ).next { |doc, user|
        new(
          user:,
          title: doc.at_css('meta[property="og:title"]').attribute('content').value,
          description: doc.at_css('meta[property="og:description"]').attribute('content').value,
          uri:,
          created: Time.now # 今の所確実にタイムスタンプをとる方法がないが、取れても表示にしか使えないので今はこれでいいや
        )
      }.terminate
    end

    def icon
      user.icon
    end
  end
end
