import SwiftUI

struct TextFileContentView: View {

    @ObservedObject
    var file: FileResource

    @State
    private var fileContent: String = ""

    @State
    private var loadedFile: String?

    @State
    private var loadedFileDate: Date = .now

    var body: some View {
        VStack {
            if fileContent != "" {
                HStack {
                    Button("Reload", action: reload)
                    Button("Save", action: save)
                    Spacer()
                }
                TextEditor(text: $fileContent)
                    .font(.body.monospaced())
                    .textEditorStyle(.plain)
                    .foregroundStyle(.primary)
            } else {
                Image(systemSymbol: .textDocument)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 150)
                Text("No preview available or empty file")
                    .font(.title)
            }
        }
        .foregroundStyle(.secondary)
        .onAppear(perform: loadFileContent)
        .onDisappear(perform: save)
    }

    private func loadFileContent() {
        guard fileContent == "" else {
            return
        }
        reload()
    }

    private func reload() {
        fileContent = file.textContent()
        loadedFile = file.identifier
        loadedFileDate = file.modifiedDate
        print("Loaded content of file \(file.identifier)")
    }

    private func save() {
        guard let loadedFile else {
            print("[ERROR] Text File View: No file loaded to save")
            return
        }
        guard loadedFile == file.identifier else {
            print("[ERROR] Text File View: Not saving since file changed")
            reload()
            return
        }
        guard loadedFileDate == file.modifiedDate else {
            print("Text File View: Not saving changed file \(file.identifier)")
            reload()
            return
        }
        guard fileContent != "" else {
            print("Text File View: Not saving empty file \(file.identifier)")
            return
        }
        guard file.save(textContent: fileContent) else {
            print("[ERROR] Text File View: Failed to save file \(file.identifier)")
            return
        }
        loadedFileDate = file.modifiedDate
        print("Text File View: Saved file \(file.identifier)")
    }
}
