# frozen_string_literal: true

require "jennifer"
require_relative "../rantly_extensions/data_extensions"

class Message
	module SegmentLimit
		GSM_7 = 160
		UCS_2 = 70
	end
	CHANNELS = ["sms", "mms", "rbm"]

	# @param redis [RedisClient]
	def initialize(redis)
		@redis = redis
	end

	include Jennifer.rant(self) { |registered, jid, dir, top_level_to|
		from {
			case dir
			when "in"
				choose(nanpa_phone, shortcode)
			when "out"
				nanpa_phone
			end
		}
		to derived_from(:from) {
			case dir
			when "in"
				array(integer(4)) { nanpa_phone }
			when "out"
				array(integer(4)) { nanpa_phone } +
					[top_level_to] +
					array(integer(4)) { nanpa_phone }
			end
		}
		owner derived_from(:to, :from) { |to, from|
			case dir
			when "in"
				choose(*to)
			when "out"
				from
			end
		}
		direction { dir }
		time { iso8601 }
		text {
			# From bandwidth docs
			# ```
			# message.to: Empty text/string. Message text content will not be sent in callback.
			# ```
			case dir
			when "in"
				string
			when "out"
				""
			end
		}
		media {
			choose(nil, array(range(0, 10)) { media_url })
		}
		stanza_id(transient: true) { string(:alnum) }
		resourcepart(transient: true) { string }
		tag derived_from(:stanza_id, :resourcepart) { |stanza_id, resourcepart|
			[stanza_id, resourcepart].join(" ")
		}
		id { string }
		application_id { string }
		channel { choose(*CHANNELS) }
		segment_count derived_from(:channel, :text) { |channel, text|
			next 0 unless text

			case channel
			when "mms"
				1
			when "sms", "rbm"
				segment_limit = choose(SegmentLimit::GSM_7, SegmentLimit::UCS_2)
				(text.size / segment_limit).floor +
					(text.size % segment_limit == 0 ? 0 : 1)
			end
		}
		description { string }
		errorCode {
			case dir
			when "out" then range(4000, 5999).to_s
			when "in" then nil
			end
		}
		redis_state derived_from(:owner), transient: true do |owner|
			@redis.reset!
			@redis.set("catapult_jid-", "HERE")
			next unless registered

			@redis.set("catapult_jid-#{owner}", jid)
		end
	}
end
