module Twitch
  class UserChannelProperty < Service::Base
    self.service_endpoint = Settings.channel_properties.endpoint
    self.primary_attribute = :id

    attributes :id, :name, :transcode_type, :delay_length, :hls_segment_duration, :source_restricted, :save_vods, :delay_controls_enabled, :stream_key, :authorized_stream_keys, :latency, :drm_enabled, :num_backup_streams_allowed, :backup_controls_enabled, :disconnect_slate_duration, :disconnect_slate_controls_enabled

    validates :id, :transcode_type, :delay_length, :hls_segment_duration, :source_restricted, :save_vods, :delay_controls_enabled, :drm_enabled, presence: true

    def self.find(id, options = {})
      response = get "/v1.0/channel/id/#{id}", params: options

      if response.success?
        from_attributes(response.body)
      else
        from_errors(map_to_known_error(response))
      end
    end

    def self.from_attributes(params)
      channel = super(params)
      channel.authorized_stream_keys ||= []
      channel.authorized_stream_keys.map! { |ask| AuthorizedStreamKey.new(ask) }
      return channel
    end

    def self.map_to_known_error(response)
      msg = response.body['Msg']
      if msg.downcase.start_with?('not allowed to broadcast')
        msg = "#{msg}, likely due to 2FA not being enabled."
      end
      "#{response.body['Status']} #{response.body['Code']}: #{msg}"
    end

    def update(params)
      body = params.each_with_object({}) do |(key, value), hash|
        hash[key] = {"value" => value}
      end
      response = put "/v1.0/channel/id/#{primary_attribute_value}", body: body.to_json
      self.errors = "#{response.body['Status']} #{response.body['Code']}: #{response.body['Msg']}" unless response.success?
      response.success?
    end

    def regenerate_stream_key
      response = put "/v1.0/channel/id/#{primary_attribute_value}/regenerate_stream_key"
      self.errors = "#{response.body['Status']} #{response.body['Code']}: #{response.body['Msg']}" unless response.success?
      response.success?
    end

    def remove_authorized_stream_key(params)
      url = "/v1.0/channel/id/#{primary_attribute_value}/authorized_stream_key/#{params['email']}"
      response = delete url
      self.errors = "#{response.body['Status']} #{response.body['Code']}: #{response.body['Msg']}" unless response.success?
      response.success?
    end

    def add_authorized_stream_key(params)
      body = {"email" => params["authorized_stream_key"]["email"]}
      response = post "/v1.0/channel/id/#{primary_attribute_value}/authorized_stream_key", body: body.to_json
      self.errors = "#{response.body['Status']} #{response.body['Code']}: #{response.body['Msg']}" unless response.success?
      response.success?
    end

    def disconnect
      response = Digestion::Stream.disconnect(name)
      self.errors = "#{response.body['StatusCode']} #{response.body['ID']}: #{response.body['Message']}" unless response.success?
      response.success?
    end

    def user
      @user ||= Twitch::User.find(id)
      @user
    end
  end
end
