#!/usr/local/bin/python3.sh
# -*-mode: python; indent-tabs-mode: nil; py-indent-offset: 4; coding: utf-8 -*

import sys
import os
import atexit
import traceback
import functools
import asyncio
import time
import qasync
import threading

from PyQt5.QtWidgets import (QProgressBar, QWidget, QVBoxLayout)
# from PySide2.QtWidgets import QApplication, QProgressBar
from qasync import QEventLoop, QThreadExecutor
from qasync import asyncSlot, asyncClose, QApplication

from phantompy import Render
from lookupdns import LookFor

global LOG
import logging
import warnings
warnings.filterwarnings('ignore')
LOG = logging.getLogger()

class MainWindow(QWidget):
    """Main window."""
    def __init__(self):
        super().__init__()

        self.setLayout(QVBoxLayout())
        self.progress = QProgressBar()
        self.progress.setRange(0, 99)
        self.layout().addWidget(self.progress)

async def main(app):
    def close_future(future, loop):
        loop.call_later(10, future.cancel)
        future.cancel()

    loop = asyncio.get_running_loop()
    future = asyncio.Future()
    app.ldone = []

    getattr(app, "aboutToQuit").connect(
        functools.partial(close_future, future, loop)
        )

    if False:
        progress = QProgressBar()
        progress.setRange(0, 99)
        progress.show()
    else:
        mw = MainWindow()
        progress = mw.progress
        mw.show()
#    LOG.info(f"calling first_50 {r}")
#    await first_50(progress, r)
    LOG.info(f"calling last_50 {r}")
    o = QThreadExecutor(max_workers=1)
    app.o = o
    with o as executor:
        await loop.run_in_executor(executor, functools.partial(last_50, progress, sys.argv[1:], app), loop)
        LOG.info(f" {dir(o)}")

    LOG.info(f"awaiting {future}")
    await future
    return True

async def first_50(progress, r=None):
    progress.setValue(5)
    LOG.info(f"first_50 {r}")
    if r is not None:
        # loop = asyncio.get_running_loop()
        # LOG.info(f"first_50.r.run {r}")
        # loop.call_soon_threadsafe(r.run, r.url, r.outfile, r.jsfile)
        # r.run( r.url, r.outfile, r.jsfile)
        for i in range(50):
            # LOG.info(f"first_50 {r.progress} {i}")
            # if  r.progress >= 100: break
            # progress.setValue(max(r.progress,i))
            progress.setValue(i)
            await asyncio.sleep(.1)
        return
    for i in range(50):
        LOG.info(f"first_50 {r} {i}")
        loop.call_soon_threadsafe(progress.setValue, i)
        time.sleep(1)

def last_50(progress, largs, app, loop):
    url = largs[0]
    outfile = largs[1]
    jsfile = largs[2] if len(largs) > 2 else None
    r = Render(app, do_print=False, do_save=True)
    uri = url.strip()
    loop.call_soon_threadsafe(r.run, uri, outfile, jsfile)
    time.sleep(1)
    for i in range(50, 100):
        j = len(app.ldone) # r.progress
        if j == 100:
            LOG.info(f"last_50 None {i} {j}")
        else:
            LOG.debug(f"last_50 None {i} {j}")
        loop.call_soon_threadsafe(progress.setValue, i)
        time.sleep(1)

if __name__ == '__main__':
    url = 'https://dns.google/resolve?name=6D6EC2A2E2ED8BFF2D4834F8D669D82FC2A9FA8D.for-privacy.net&type=TXT&cd=true&do=true'
    outfile = '/tmp/test1.pdf'
    jsfile = '/tmp/test1.js'
    from exclude_badExits import vsetup_logging
    vsetup_logging(10)
    app = QApplication([])
    #?
    loop = qasync.QEventLoop(app)
#NOT    loop = asyncio.get_event_loop()
    asyncio._set_running_loop(loop)
    asyncio.events._set_running_loop(loop)
    r = Render(app, do_print=False, do_save=True)
    #loop.call_soon_threadsafe(r.run, url, outfile, jsfile)
    r.run(url, outfile, jsfile)
    app.rs = [r]
    for i in range(20):
        for elt in app.rs:
            print (elt.percent)
            time.sleep(2)
    try:
        qasync.run(main(app))
    except asyncio.exceptions.CancelledError:
        sys.exit(0)
    except RuntimeError as e:
        LOG.debug('Fixme')
        sys.exit(0)
    except KeyboardInterrupt:
        sys.exit(0)
    else:
        val = 0
        sys.exit(val)
