#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import UnityMail.imaplib2 as imaplib
from threading import *

class Idler(object):

    def __init__(self, oConnection, fnCallback):

        self.oThread = Thread(target=self.idle)
        self.oConnection = oConnection
        self.oEvent = Event()
        self.fnCallback = fnCallback
        self.bNeedSync = False

    def start(self):

        self.oThread.start()

    def stop(self):

        self.oEvent.set()

    def join(self):

        self.oThread.join()

    def idle(self):

        while True:

            if self.oEvent.isSet():
                return

            self.bNeedSync = False

            def callback(lstArgs):

                if not self.oEvent.isSet():

                    self.bNeedSync = True
                    self.oEvent.set()

            try:

                self.oConnection.oImap.idle(callback=callback)

            except imaplib.IMAP4.abort as oError:

                self.fnCallback(self.oConnection)
                return

            self.oEvent.wait()

            if self.bNeedSync:

                self.oEvent.clear()
                self.fnCallback(self.oConnection)
