import SwiftUI

struct InitialSetupView: View {

    @EnvironmentObject
    private var content: Content

    @Environment(\.dismiss)
    private var dismiss

    @State
    private var message: String?

    var body: some View {
        VStack {
            Text("No Database Loaded")
                .font(.title)
                .padding()
            Text("To start editing the content of a website, create a new database or load an existing one. Open a folder with an existing database, or choose an empty folder to create a new project.")
                .multilineTextAlignment(.center)
            Button("Select folder", action: selectContentPath)
                .padding()
            if let message {
                Text(message)
                    .padding(.bottom)
                    .lineLimit(10)
            }
        }
        .padding()
        .frame(maxWidth: 350)
    }

    private func selectContentPath() {
        let panel = NSOpenPanel()
        // Sets up so user can only select a single directory
        panel.canChooseFiles = false
        panel.canChooseDirectories = true
        panel.allowsMultipleSelection = false
        panel.showsHiddenFiles = false
        panel.title = "Select the database folder"

        let response = panel.runModal()
        guard response == .OK else {
            set(message: "Failed to select a folder: \(response)")
            return
        }
        guard let url = panel.url else {
            set(message: "No folder url found")
            return
        }

        guard content.storage.save(contentPath: url) else {
            set(message: "Failed to set content path")
            return
        }

        DispatchQueue.global().async {
            let loader = ModelLoader(content: content, storage: content.storage)
            let result = loader.load()
            guard result.errors.isEmpty else {
                let message = "Failed to load database\n" + result.errors.sorted().joined(separator: "\n")
                set(message: message)
                return
            }

            DispatchQueue.main.async {
                content.files = result.files
                content.posts = result.posts
                content.pages = result.pages
                content.tags = result.tags
                content.settings = result.settings
                content.tagOverview = result.tagOverview
                dismiss()
            }
        }
    }

    private func set(message: String) {
        DispatchQueue.main.async {
            self.message = message
        }
    }
}
