#!/usr/bin/python3.6
"""
Refresh tasks that have bugzilla bugs in an open state to prevent them from getting deleted by
retrace-server-cleanup tool.
"""

import sys
import time

from pathlib import Path

import bugzilla

from retrace.retrace import RetraceTask
from retrace.config import Config

CONFIG = Config()

if __name__ == "__main__":

    logfile = Path(CONFIG["LogDir"], "bugzilla-refresh.log")

    with logfile.open("a") as log:
        log.write(time.strftime("[%Y-%m-%d %H:%M:%S] Running bugzilla refresh\n"))

        # connect to bugzilla
        bz_url = CONFIG["BugzillaURL"]
        bz_creds = CONFIG["BugzillaCredentials"]
        bz_status_list = CONFIG.get_list("BugzillaStatus")

        try:
            bzapi = bugzilla.Bugzilla(url=bz_url, cookiefile=None, tokenfile=None)
        except (bugzilla.BugzillaError, ValueError) as e:
            log.write("Exception: {0}".format(e))
            sys.exit(1)

        if not bzapi.logged_in and bz_creds:
            bzapi.readconfig(bz_creds)
            try:
                bzapi.connect()
            except (bugzilla.BugzillaError, ValueError) as e:
                log.write("Exception: {0}".format(e))

        if bzapi.logged_in:
            log.write("Successfuly logged in as {0}.\n".format(bzapi.user))
        else:
            log.write("Not logged in. Continue as anonymous user.\n")

        try:
            files = list(Path(CONFIG["SaveDir"]).iterdir())
        except OSError as ex:
            files = []
            log.write("Error listing task directory: %s\n" % ex)

        for filepath in files:
            try:
                task = RetraceTask(filepath.name)
            except Exception:
                continue

            if task.has_bugzillano():
                bz_id_list = task.get_bugzillano()
                if not bz_id_list:
                    continue

                bz_list = bzapi.getbugs(bz_id_list)

                for bgz in bz_list:
                    if bgz and bgz.status not in bz_status_list:
                        log.write("Modifying time of the task %s\n" % filepath.name)
                        task.reset_age()
                        break
