using GLib;

public class Conversation : Object {
    public string guid { get; set; default = ""; }
    public string last_message_preview { get; set; default = ""; }
    public int64 date { get; set; default = 0; }
    public string[] participants { get; set; default = new string[0]; }
    public int unread_count { get; set; default = 0; }

    public bool is_unread { get { return unread_count > 0; } }

    public string display_name {
        owned get {
            if (_display_name != null && _display_name.length > 0) {
                return _display_name;
            }

            if (participants.length == 1) {
                return participants[0];
            }

            if (participants.length > 1) {
                return string.joinv(", ", participants);
            }

            return "Untitled";
        }
    }

    private string? _display_name = null;

    public Conversation.from_hash_table(HashTable<string, Variant> conversation_data) {
        guid = conversation_data["guid"].get_string();

        if (conversation_data.contains("last_message_preview")) {
            last_message_preview = conversation_data["last_message_preview"].get_string();
        }

        if (conversation_data.contains("participants")) {
            participants = conversation_data["participants"].dup_strv();
        }

        if (conversation_data.contains("unread_count")) {
            unread_count = conversation_data["unread_count"].get_int32();
        }

        if (conversation_data.contains("date")) {
            date = conversation_data["date"].get_int64();
        }

        if (conversation_data.contains("display_name")) {
            _display_name = conversation_data["display_name"].get_string();
        }
    }

    public bool equals(Conversation other) {
        if (other == null) return false;
        if (guid != other.guid) return false;
        if (date != other.date) return false;
        if (unread_count != other.unread_count) return false;
        if (last_message_preview != other.last_message_preview) return false;
        if (_display_name != other._display_name) return false;
        
        // Compare participants arrays
        if (participants.length != other.participants.length) return false;
        for (int i = 0; i < participants.length; i++) {
            if (participants[i] != other.participants[i]) return false;
        }
        
        return true;
    }
}