SegmentedMessage constructor

SegmentedMessage(
  1. String message, [
  2. SmsEncoding encoding = SmsEncoding.auto,
  3. bool smartEncoding = false
])

Constructor for the SegmentedMessage class.

message : The message content to be segmented and encoded. encoding : The desired encoding format (defaults to auto-detection). smartEncoding : Whether to use smart encoding for character replacement.

Implementation

SegmentedMessage(String message,
    [SmsEncoding encoding = SmsEncoding.auto, bool smartEncoding = false])
    : encoding = encoding {
  GraphemeSplitter splitter = GraphemeSplitter();

  // Check if the specified encoding is valid
  if (!ValidEncodingValues.values.any((e) => e.name == encoding.name)) {
    throw ('Encoding $encoding not supported');
  }

  // Apply smart encoding if enabled
  if (smartEncoding) {
    message = message
        .split('')
        .map((char) =>
            smartEncodingMap[char] ?? char) // Fallback to original character
        .join('');
  }

  /// Split message into graphemes and process line breaks
  graphemes = splitter.splitGraphemes(message).fold<List<String>>([],
      (List<String> accumulator, String grapheme) {
    if (grapheme == '\r\n') {
      accumulator.addAll(grapheme.split('')); // Separate '\r\n' characters
    } else {
      accumulator.add(grapheme); // Add the grapheme as is
    }
    return accumulator;
  });

  /// Count the number of Unicode scalars in the message
  numberOfUnicodeScalars = message.runes.length;

  /// Determine the encoding type for the message
  String? encodingName;
  if (encoding == SmsEncoding.auto) {
    encodingName = _hasAnyUCSCharacters(graphemes) ? 'ucs2' : 'gsm7';
  } else {
    if (encoding == SmsEncoding.gsm7 && _hasAnyUCSCharacters(graphemes)) {
      throw ('The string provided is incompatible with GSM-7 encoding');
    }
    encodingName = encoding.name;
  }

  /// Encode the characters based on the determined encoding
  encodedChars = _encodeChars(graphemes, encodingName);

  /// Count the number of characters based on encoding
  numberOfCharacters = encodingName == SmsEncoding.ucs2.name
      ? graphemes.length
      : _countCodeUnits(encodedChars);

  /// Build segments from encoded characters
  segments = _buildSegments(encodedChars);

  /// Detect the line break style in the message
  lineBreakStyle = _detectLineBreakStyle(message);

  /// Check for any warnings in the message content
  warnings = _checkForWarnings(lineBreakStyle);
}