# frozen_string_literal: true

require 'open-uri'

module Mixi2
  class User < Diva::Model
    include Diva::Model::UserMixin

    register :mixi2_user, name: 'mixi2 ユーザー', timeline: false

    field.string :name, required: true
    field.string :title, required: true
    field.string :description, required: true
    field.uri :uri, required: true
    field.uri :icon_url, required: true

    USER_URI_REGEXP = %r!\Ahttps://mixi.social/@(?<screen_name>[A-Za-z0-9_]+)\z!

    handle USER_URI_REGEXP do |uri|
      uri = Diva::URI(uri)
      Thread.new {
        Nokogiri::HTML(uri.to_uri.open(&:read))
      }.next { |doc|
        new(
          name: USER_URI_REGEXP.match(uri.to_s)['screen_name'],
          title: doc.at_css('meta[property="og:title"]').attribute('content').value,
          description: doc.at_css('meta[property="og:description"]').attribute('content').value,
          uri:,
          icon_url: doc.at_css('meta[property="og:image"]').attribute('content').value
        )
      }.terminate
    end

    def icon
      Plugin.collect(:photo_filter, icon_url, Pluggaloid::COLLECT).lazy.map { |photo|
        Plugin.filtering(:miracle_icon_filter, photo)[0]
      }.first
    end
  end
end
