class SvelteOnRails::TurboStream

def self.configs

def self.configs
  @configs ||= begin
                 conf = SvelteOnRails::Configuration.instance
                 unless conf.configs[:turbo_stream]
                   raise '[svelte-on-rails] missing configuration: :turbo_stream'
                 end
                 unless conf.configs[:turbo_stream]['target_html_id']
                   raise '[svelte-on-rails] missing configuration: turbo_stream/target_html_id'
                 end
                 unless conf.configs[:turbo_stream]['channel']
                   raise '[svelte-on-rails] missing configuration: turbo_stream/channel'
                 end
                 conf.configs[:turbo_stream]
               end
end

def self.dispatch(component = nil, event_detail = nil, event: 'stream-action', selector: nil, channel: nil)

def self.dispatch(component = nil, event_detail = nil, event: 'stream-action', selector: nil, channel: nil)
  utils = SvelteOnRails::Lib::Utils
  conf = SvelteOnRails::Configuration.instance
  _comp = if component
            utils.validate_filename(component)
            "/#{conf.components_folder + component}"
          end
  if event != 'stream-action' && !selector
    raise "Another event name than the default one is only possible together with a selector"
  end
  args = {
    eventDetail: event_detail,
    component: _comp,
    event: event,
    selector: selector
  }
  args_enc = Base64.strict_encode64(args.to_json)
  Turbo::StreamsChannel.send(
    "broadcast_append_to",
    channel || configs['channel'],
    target: configs['target_html_id'],
    content: "<div style=\"display: none;\" data-controller=\"svelte-on-rails-turbo-stream\" data-args=\"#{args_enc}\"></div>"
  )
end

def self.dispatch_by_selector(selector, event_detail = nil, event: 'stream-action', channel: nil)

def self.dispatch_by_selector(selector, event_detail = nil, event: 'stream-action', channel: nil)
  if event != 'stream-action' && !selector
    raise "Another event name than the default one is only possible together with a selector"
  end
  args = {
    eventDetail: event_detail,
    component: ':false:',
    event: event,
    selector: selector
  }
  args_enc = Base64.strict_encode64(args.to_json)
  Turbo::StreamsChannel.send(
    "broadcast_append_to",
    require_channel(channel || configs['channel']),
    target: configs['target_html_id'],
    content: "<div style=\"display: none;\" data-controller=\"svelte-on-rails-turbo-stream\" data-args=\"#{args_enc}\"></div>"
  )
end

def self.require_channel(channel)

def self.require_channel(channel)
  unless channel.present?
    raise 'Missing attribute or configuration: turbo_stream/channel'
  end
  channel
end