
import SwiftUI
import GRDB

struct CoreDuetView: View {
    @State var contacts = [Row]()
    @State var interactions = [Row]()
    @State var attachments = [Row]()
    @State var contactsMap = [Int: Row]()
    @State var loaded = false

    var body: some View {
        List {
            if loaded {
                NavigationLink("Contacts: \(contacts.count)", destination: DuetContactsView(rows: contacts))
                NavigationLink("Interactions: \(interactions.count)", destination: DuetInteractionsView(rows: interactions, contactsMap: contactsMap))
                NavigationLink("Attachments: \(attachments.count)", destination: DuetAttachmentsView(rows: attachments))
            }
        }.onAppear(perform: {
            do {
                let dbPool = try DatabasePool(path: coreDuetPath)
                contacts = try dbPool.read { db in
                    return try Row.fetchAll(db, sql: "SELECT * FROM ZCONTACTS")
                }
                interactions = try dbPool.read { db in
                    return try Row.fetchAll(db, sql: "SELECT * FROM ZINTERACTIONS")
                }
                attachments = try dbPool.read { db in
                    return try Row.fetchAll(db, sql: "SELECT * FROM ZATTACHMENT")
                }
                contactsMap = Dictionary(uniqueKeysWithValues: contacts.map { ($0["Z_PK"]!, $0) })
            } catch {
                print(error)
            }
            loaded = true
        })
    }
}

struct CoreDuetView_Previews: PreviewProvider {
    static var previews: some View {
        CoreDuetView()
    }
}
