#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence) 
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED.  OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import os
import sys

from openeye import oechem
from openeye import oesitehopper


def main(args):
    itf = oechem.OEInterface()
    oechem.OEConfigure(itf, interface)
    if oechem.OECheckHelp(itf, args):
        return 0
    if not oechem.OEParseCommandLine(itf, args):
        return 1

    dbname = itf.GetString("-shdb")
    outfile = None
    if itf.HasString("-out"):
        outfile = itf.GetString("-out")

    shdb = oesitehopper.OESiteHopperDatabase()
    if not os.path.isfile(dbname) or not shdb.Open(dbname, oesitehopper.OESiteHopperDatabaseMode_READONLY):
        print(f"unable to open {dbname} for reading")
        return 1

    if outfile and not oechem.OEIsWriteableDesignUnit(outfile):
        print(f"{outfile} is not a valid OEDesignUnit filename")
        return 1

    if itf.HasUnsignedInt("-index") and itf.HasString("-title"):
        print("can't use both -index and -title together")
        return 1

    du = oechem.OEDesignUnit()
    if itf.HasUnsignedInt("-index"):
        index = itf.GetUnsignedInt("-index")
        if shdb.GetDesignUnit(du, index):
            if outfile and oechem.OEWriteDesignUnit(outfile, du):
                print(f"Wrote DU {du.GetTitle()} to {outfile}")
                return 0
            else:
                print(f"ID: {index}, TITLE: {shdb.GetTitle(index)}")
        else:
            print("unable to retrieve DU with IDX = {index}")
            return 1
    elif itf.HasString("-title"):
        title = itf.GetString("-title")
        indices = shdb.GetIDByTitle(title)
        if len(indices) == 0:
            print("No DUs found with title matching '{title}'")
            return False
        ofs = None
        if outfile:
            ofs = oechem.oeofstream(outfile)
        for index in indices:
            if ofs and shdb.GetDesignUnit(du, index):
                oechem.OEWriteDesignUnit(ofs, du)
                print(f"Wrote DU {du.GetTitle()} to {outfile}")
            else:
                print(f"ID: {index}, TITLE: {shdb.GetTitle(index)}")
    else:
        print("Please try -index or -title for DUs to extract")


interface = """
!BRIEF get_designunit.py [-index IDX | -title TITLE] <shdb> <oedu file>

!CATEGORY I/O

    !PARAMETER -shdb 1
        !TYPE string
        !REQUIRED true
        !VISIBILITY simple
        !BRIEF Input OESiteHopperDatabase
    !END

    !PARAMETER -out 2
        !TYPE string
        !REQUIRED false
        !VISIBILITY simple
        !BRIEF Output .oedu file. If empty, just print out titles of matched DUs
    !END
!END

!CATEGORY Choice 99
    !PARAMETER -index
        !TYPE unsigned
        !REQUIRED false
        !VISIBILITY simple
        !BRIEF Single index of OEDU to extract from database
    !END

    !PARAMETER -title
        !TYPE string
        !REQUIRED false
        !VISIBILITY simple
        !BRIEF Title for substring match to extract from database
    !END
!END
"""

if __name__ == "__main__":
    sys.exit(main(sys.argv))
