import config

class GST:

    @staticmethod
    def get_unreleased_gst():

        connection = config.get_db_connection()
        cursor = connection.cursor(dictionary=True)

        try:
            # ----------- Invoices -----------
            cursor.callproc('GetAllInvoicesBasic')
            invoices = []
            for result in cursor.stored_results():
                invoices = result.fetchall()


            # ----------- GST Releases -----------
            cursor.callproc('GetAllGSTReleasesBasic')
            gst_releases = []
            for result in cursor.stored_results():
                gst_releases = result.fetchall()

            gst_invoice_nos = {
                g['Invoice_No']
                for g in gst_releases
                if g['Invoice_No']
            }

            gst_basic_amounts = {
                float(g['Basic_Amount'])
                for g in gst_releases
                if g['Basic_Amount'] is not None
            }

            unreleased = []

            for inv in invoices:

                match_by_invoice = inv['Invoice_No'] in gst_invoice_nos

                match_by_gst_amount = float(
                    inv.get('GST_SD_Amount') or 0
                ) in gst_basic_amounts

                if not (match_by_invoice or match_by_gst_amount):
                    unreleased.append(inv)

            return unreleased

        finally:
            cursor.close()
            connection.close()
            