//
//  Richtext.swift
//  oosxl
//

import cxx_oosxl

public class Richtext: Equatable, @unchecked Sendable {
    let handle: RichtextHandle

    init(withHandle handle: RichtextHandle) {
        self.handle = handle
    }

    deinit {
        rt_release(handle)
    }

    public var segmentCount: Int {
        return Int(rt_segments_num(handle))
    }

    public var plainText: String {
        if let text = rt_plain_text(handle) {
            return String(cString: text)
        }
        return ""
    }

    public func segment(at index: Int) -> (text: String, style: Style)? {
        var styleHandle: StyleHandle? = nil
        if let text = rt_text(handle, Int32(index), &styleHandle) {
            return (String(cString: text), Style(withHandle: styleHandle!))
        }

        return nil
    }

    public func append(text: String, style: Style? = nil) {
        rt_append(self.handle, text, style?.handle)
    }

    public func insert(text: String, at index: Int, style: Style? = nil) {
        rt_insert(self.handle, Int32(index), text, style?.handle)
    }

    public func remove(at index: Int) {
        rt_remove(handle, Int32(index))
    }

    public func modify(at index: Int, text: String, style: Style? = nil) {
        rt_modify(self.handle, Int32(index), text, style?.handle)
    }

    public static func == (lhs: Richtext, rhs: Richtext) -> Bool {
        return lhs.handle == rhs.handle
    }
}
