import os
from MailPing import mail, maildir, fileutil

def process(statedir):
    def _processEmail(subdir, filename):
        ident = mail.getID(os.path.join(subdir, filename))
        if ident is None:
            maildir.create(os.path.join(subdir, '..', '..', 'junk'))
            os.rename(os.path.join(subdir, filename),
                      os.path.join(subdir, '..', '..', 'junk', 'new', filename))
        else:
            pending = os.path.join(subdir,
                                   '..', '..',
                                   'pending', ident)
            timestamp = fileutil.getTime(pending)
            if timestamp < 0:
                maildir.create(os.path.join(subdir, '..', '..', 'broken'))
                os.rename(os.path.join(subdir, filename),
                          os.path.join(subdir, '..', '..', 'broken', 'new', filename))
            else:
                lastSuccess = fileutil.getTime(os.path.join(subdir,
                                                            '..', '..',
                                                            'success'))
                if timestamp > lastSuccess:
                    os.rename(os.path.join(subdir, filename),
                              os.path.join(subdir, '..', '..', 'success.msg'))
                    os.rename(pending,
                              os.path.join(subdir, '..', '..', 'success'))

                    deliveryTime = maildir.getTimeFromFilename(filename)
                    if isinstance(deliveryTime, int):
                        # If delivery time has only 1 second precision,
                        # truncate current time to same accuracy, to avoid
                        # deliveries seeming to happen before creation
                        # of the pending file.
                        #
                        # The race could trigger if mailping-cron is
                        # run in a tight loop, or if it is later changed
                        # to do probe sending before incoming processing.
                        timestamp = int(timestamp)
                    if deliveryTime is not None and deliveryTime >= timestamp:
                        fileutil.writeFile(os.path.join(subdir, '..', '..', 'latency'),
                                           '%f\n' % (deliveryTime - timestamp))
                else:
                    os.unlink(os.path.join(subdir, filename))
                    os.unlink(pending)

    maildir.process(os.path.join(statedir, 'incoming'),
                    _processEmail)
