//
//  Document.swift
//  oosxl
//

import Foundation
import cxx_oosxl

public enum SaveError: Error {
    case failed(reason: String)
}

public class Document {
    let handle: DocumentHandle

    init(with handle: DocumentHandle) {
        self.handle = handle
    }

    deinit {
        doc_release(handle)
        print("runtime message while release docuemnt: \(oosxl.runmsg)")
    }

    public func workbook() -> Workbook {
        let handle: WorkbookHandle? = doc_get_workbook(self.handle)
        return handle.map { Workbook(withHandle: $0) }!
    }

    public func save(to filename: String? = nil) throws {
        let result =
            filename?.withCString { file in
                doc_save(self.handle, file)
            } ?? doc_save(self.handle, nil)

        if result == 0 {
            throw SaveError.failed(reason: oosxl.runmsg)
        }
    }
}
