from datetime import datetime


def outputSPDX(doc, spdxPath):
    """
    Write SPDX doc, package and files content to disk.

    Arguments:
        - doc: BuilderDocument
        - spdxPath: path to write SPDX content
    Returns: True on success, False on error.
    """
    try:
        with open(spdxPath, 'w') as f:
            # write document creation info section
            f.write(f"""SPDXVersion: SPDX-2.2
DataLicense: CC0-1.0
SPDXID: SPDXRef-DOCUMENT
DocumentName: {doc.config.documentName}
DocumentNamespace: {doc.config.documentNamespace}
Creator: Tool: cmake-spdx
Created: {datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")}
""")
            # write any external document references
            for extRef in doc.config.extRefs:
                f.write(f"ExternalDocumentRef: {extRef[0]} {extRef[1]} {extRef[2]}:{extRef[3]}\n")
            f.write(f"\n")

            # write package sections
            for pkg in doc.packages.values():
                f.write(f"""##### Package: {pkg.name}

PackageName: {pkg.name}
SPDXID: {pkg.spdxID}
PackageDownloadLocation: {pkg.downloadLocation}
FilesAnalyzed: true
PackageVerificationCode: {pkg.verificationCode}
PackageLicenseConcluded: {pkg.licenseConcluded}
""")
                for licFromFiles in pkg.licenseInfoFromFiles:
                    f.write(f"PackageLicenseInfoFromFiles: {licFromFiles}\n")
                f.write(f"""PackageLicenseDeclared: {pkg.licenseDeclared}
PackageCopyrightText: NOASSERTION

Relationship: SPDXRef-DOCUMENT DESCRIBES {pkg.spdxID}

""")

                # write file sections
                for bf in pkg.files:
                    f.write(f"""FileName: {bf.name}
SPDXID: {bf.spdxID}
FileChecksum: SHA1: {bf.sha1}
""")
                    if bf.sha256 != "":
                        f.write(f"FileChecksum: SHA256: {bf.sha256}\n")
                    if bf.md5 != "":
                        f.write(f"FileChecksum: MD5: {bf.md5}\n")
                    f.write(f"LicenseConcluded: {bf.licenseConcluded}\n")
                    if len(bf.licenseInfoInFile) == 0:
                        f.write(f"LicenseInfoInFile: NONE\n")
                    else:
                        for licInfoInFile in bf.licenseInfoInFile:
                            f.write(f"LicenseInfoInFile: {licInfoInFile}\n")
                    f.write(f"FileCopyrightText: {bf.copyrightText}\n\n")

            # we're done for now; will do other relationships later
            return True

    except OSError as e:
        print(f"Error: Unable to write to {spdxPath}: {str(e)}")
        return False