import sys
import time

from entrypoint2 import entrypoint

import pyscreenshot
from pyscreenshot.util import proc


def run(force_backend, n, childprocess, bbox=None):
    sys.stdout.write("%-20s\t" % force_backend)
    sys.stdout.flush()  # before any crash

    try:
        start = time.time()
        for _ in range(n):
            pyscreenshot.grab(
                backend=force_backend, childprocess=childprocess, bbox=bbox
            )
        end = time.time()
        dt = end - start
        s = "%-4.2g sec\t" % dt
        s += "(%5d ms per call)" % (1000.0 * dt / n)
        sys.stdout.write(s)
    finally:
        print("")


# TODO: add default
def run_all(n, childprocess_param, virtual_only=True, bbox=None):
    print("")
    print("n=%s" % n)
    print("------------------------------------------------------")

    if bbox:
        x1, y1, x2, y2 = map(str, bbox)
        bbox = ":".join(map(str, (x1, y1, x2, y2)))
        bboxpar = ["--bbox", bbox]
    else:
        bboxpar = []
    debugpar = []
    debugpar = ["--debug"]
    for x in pyscreenshot.backends():
        if virtual_only and x == "gnome-screenshot":  # TODO: remove
            continue
        p = proc(
            "pyscreenshot.check.speedtest",
            ["--backend", x, "--childprocess", childprocess_param] + bboxpar + debugpar,
        )
        print(p.stdout)


@entrypoint
def speedtest(virtual_display=False, backend="", childprocess="", bbox=""):
    """Performance test of all back-ends. 
    
    :param virtual_display: run with Xvfb
    :param bbox: bounding box coordinates x1:y1:x2:y2
    :param backend: back-end can be forced if set (example:scrot, wx,..),
                    otherwise back-end is automatic
    :param childprocess: pyscreenshot parameter childprocess (0/1)
    """
    childprocess_param = childprocess
    if childprocess == "":
        childprocess = None
    elif childprocess == "0":
        childprocess = False
    elif childprocess == "1":
        childprocess = True
    else:
        raise ValueError("invalid childprocess value")

    n = 10
    if bbox:
        x1, y1, x2, y2 = map(int, bbox.split(":"))
        bbox = x1, y1, x2, y2
    else:
        bbox = None

    def f(virtual_only):
        if backend:
            try:
                run(backend, n, childprocess, bbox=bbox)
            except pyscreenshot.FailedBackendError:
                pass
        else:
            run_all(n, childprocess_param, virtual_only=virtual_only, bbox=bbox)

    if virtual_display:
        from pyvirtualdisplay import Display

        with Display(visible=0):
            f(virtual_only=True)
    else:
        f(virtual_only=False)

@@ -1,12 +1,27 @@
+import logging%0A
 import sys%0Ai
@@ -32,16 +32,36 @@
 t time%0A%0A
+import pyscreenshot%0A
 from ent
@@ -86,37 +86,16 @@
 trypoint
-%0A%0Aimport pyscreenshot
 %0Afrom py
@@ -268,16 +268,80 @@
  crash%0A%0A
+    if force_backend == %22default%22:%0A        force_backend = None%0A
     try:
@@ -718,28 +718,8 @@
 )%0A%0A%0A
-# TODO: add default%0A
 def 
@@ -776,24 +776,41 @@
 bbox=None):%0A
+    debug = True%0A
     print(%22%22
@@ -1081,22 +1081,22 @@
     
+if 
 debug
-par = %5B%5D%0A
+:%0A    
     
@@ -1126,41 +1126,125 @@
     
-for x in pyscreenshot.backends():
+else:%0A        debugpar = %5B%5D%0A    for x in %5B%22default%22%5D + pyscreenshot.backends():%0A        backendpar = %5B%22--backend%22, x%5D
 %0A   
@@ -1409,24 +1409,8 @@
    %5B
-%22--backend%22, x, 
 %22--c
@@ -1463,16 +1463,29 @@
 debugpar
+ + backendpar
 ,%0A      
@@ -1805,16 +1805,25 @@
 example:
+default, 
 scrot, w
@@ -1859,24 +1859,28 @@
 herwise 
+all 
 back-end
  is auto
@@ -1875,21 +1875,20 @@
 -end
- i
 s a
-utomatic
+re tested
 %0A   

add 'default' backend