# This file was generated by mettle.genes.db.GenPy3 [ver 2.1] on Mon Feb 15 23:21:02 2021
#  Target Database = postgresql
#
import copy
import datetime
import uuid
import time
import mettle.lib
import mettle.io
import mettle.db

from bs_loco.db.tables.imsg_req_busy_changed import iMsgReqBusyChanged
from bs_loco.db.tables.omsg_req_busy_changed import oMsgReqBusyChanged

class dMsgReqBusyChanged:

    def __init__(self, dbcon: mettle.db.IConnect):
        """
        Constructor.

        :param dbcon: Mettle database connection object.
        """
        self._dbcon   = dbcon
        self._dbstmnt = None
        self.irec     = iMsgReqBusyChanged()
        self.orec     = oMsgReqBusyChanged()

    def __del__(self):
        """
        Destructor.
        """
        del self._dbstmnt

    def __enter__(self):
        """
        With statement enter.
        """
        return self

    def __exit__(self, type, value, traceback):
        """
        With statement exit.
        """
        self._destroy()

    def _destroy(self):
        if self._dbstmnt == None:
            return

        del self._dbstmnt
        self._dbstmnt = None

    def exec_deft(self,
                  limit_crit: str) -> "dMsgReqBusyChanged":
        """
        Execute the query by setting all the inputs.

        :param limit_crit: str
        :return: Self for convenience.
        """
        self.irec.limit_crit = limit_crit

        return self.exec()

    def exec(self, irec: iMsgReqBusyChanged = None) -> "dMsgReqBusyChanged":
        """
        Execute the query, optionally passing in the input rec.

        :param irec:
        :return: Self for convenience.
        """
        if irec:
            self.irec._copy_from(irec)

        self._destroy()

        self._dbstmnt = self._dbcon.statement("MsgReqBusyChanged", self._dbcon.STMNT_TYPE_READ)

        self._dbstmnt.sql("""select
  r.id,
  m.status,
  max(m.time_sent) as timesent
from
  (
    select xr.id
    from loco.msgreq xr join loco.msg xm on xr.id = xm.msgreq_id
    where xr.status = 'b' and xm.status not in ('P', 'R')
    group by xr.id
      except
    select xr.id
    from loco.msgreq xr join loco.msg xm on xr.id = xm.msgreq_id
    where xr.status = 'b' and xm.status in ('P', 'R')
    group by xr.id
  ) r
    join
  loco.msg m
    on m.msgreq_id = r.id
group by
  r.id,
  m.status
order by
  1,
  3
[limitCrit]""")

        self._dbstmnt.dynamic("[limitCrit]", self.irec.limit_crit)

        self._dbstmnt.bind_out("msgReqId", int, 8)
        self._dbstmnt.bind_out("msgStatus", str, 1)
        self._dbstmnt.bind_out("msgTime", datetime.datetime)

        self._dbcon.execute(self._dbstmnt)

        if irec:
            irec._copy_from(self.irec)

        return self

    def fetch(self) -> bool:
        """
        Fetches the next row from the executed query.

        :return: True if a row is retreived.
        """
        if not self._dbcon.fetch(self._dbstmnt):
            return False

        self.orec.msg_req_id = self._dbstmnt.result[0]
        self.orec.msg_status = self._dbstmnt.result[1]
        self.orec.msg_time = self._dbstmnt.result[2]

        return True

    def fetch_all(self, outList: oMsgReqBusyChanged.List, clearList: bool = True) -> int:
        """
        Fetch all the rows into the specified list and return the list count.

        :param outList:
        :param clearList:
        :return: Number of rows fetched.
        """
        if clearList:
            outList.clear()

        while self.fetch():
            outList.append(copy.deepcopy(self.orec))

        return len(outList)

