#!/data/data/com.termux/files/usr/bin/env python3

import sys
import time
import argparse
import subprocess
import base64
import os
from math import ceil
import re

try:
    import termuxgui as tg
except ModuleNotFoundError:
    sys.exit("termuxgui module not found. Please install the Termux:GUI python bindings: https://github.com/tareksander/termux-gui-python-bindings")


# The icon png as a base64 encoded string, so you don't have to install it as another file
icon = """iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAABhGlDQ1BJQ0MgcHJvZmlsZQAAKJF9
kT1Iw0AcxV9TpaIVh3YQKZihOlkQFXHUKhShQqgVWnUwufQLmjQkLS6OgmvBwY/FqoOLs64OroIg
+AHi5uak6CIl/i8ptIjx4Lgf7+497t4BQqPMNKtrHND0qplKxMVMdlUMvKIPEYQwDEFmljEnSUl4
jq97+Ph6F+NZ3uf+HP1qzmKATySeZYZZJd4gnt6sGpz3icOsKKvE58RjJl2Q+JHristvnAsOCzwz
bKZT88RhYrHQwUoHs6KpEU8RR1VNp3wh47LKeYuzVq6x1j35C4M5fWWZ6zQjSGARS5AgQkENJZRR
RYxWnRQLKdqPe/iHHL9ELoVcJTByLKACDbLjB/+D391a+ckJNykYB7pfbPtjBAjsAs26bX8f23bz
BPA/A1d6219pADOfpNfbWvQIGNgGLq7bmrIHXO4Ag0+GbMqO5Kcp5PPA+xl9UxYI3QK9a25vrX2c
PgBp6ip5AxwcAqMFyl73eHdPZ2//nmn19wNQn3KZKEFlDwAAAAlwSFlzAAAuIwAALiMBeKU/dgAA
AWlJREFUeNrt3NGOgjAQRmH7h/d/ZbwzaqKZtjOlzJxzu+jSj5YguPt4EBERERERERER3af26wfn
eX5s1xpYMm73ZQcWXn5YeKn3BZW92phLzfN9G55HBb3azLqr5mUaLV4dWHj1YeHVh4VX9wgre40M
r6zX4Nhqeo0PrKDX1Kiqec0OycXL/cN50KFS3G7luz+h0MOYzMttus6sx/fXDq8glzdZhDXj5Y4V
dO5zPgJdXvsv0q99Vui7Jzt/haxt4/x6bbbbRdmvHdOC2ZtmfmnNas/hdYSeHY0ud+FT6Lsn+4QY
i5XsCv7YR2qHafh/n7X+t953bQqpK7ES3xEUUtdgpb/LLKRWYxV5ciGk1mGVehompFZgFXwiLaRi
scp+i0ZIRWEV/+afkPLHQsqKhZQVCykrFlJWLKSsWEg5XJRW/styIRWCxX8rEFL2DnQCT/DMrC3a
/ys3zCywwCIiIiIiIiIiIiIiIqInKby9bxTxBeEAAAAASUVORK5CYII=
"""


parser = argparse.ArgumentParser(description="A graphical file explorer for Termux.")
parser.add_argument("--select-folder", default=False, dest="folder", action=argparse.BooleanOptionalAction, help="This shows a \"select folder\" button, outputs the current path when it is clicked, and disables starting of programs. You can wrap this with a shell alias like 'cd \"$(termux-gui-files --select-folder)\"' to navigate your shell to a folder.")

parser.add_argument("--select-file", default=False, dest="file", action=argparse.BooleanOptionalAction, help="This disables the starting of programs and instead returns the file path when a file is clicked.")

parser.add_argument("--dir", default=".", help="Sets the directory the file explorer starts in. Defaults to the current working directory.")




args = parser.parse_args()
if args.folder and args.file:
    sys.exit("You can only specify either --select-folder or --select-file")

with tg.Connection() as c:
    a = tg.Activity(c)
    a.settaskdescription("Termux file explorer", icon)
    
    
    layout = tg.LinearLayout(a)
    buttons = tg.LinearLayout(a, layout)
    buttons.setlinearlayoutparams(0)
    buttons.setheight("WRAP_CONTENT")
    
    if args.folder:
        navbutton = tg.Button(a, "select folder", buttons)
    
    treescroll = tg.NestedScrollView(a, layout)
    tree = tg.LinearLayout(a, treescroll)
    
    def centry(name):
        e = tg.TextView(a, name, tree)
        e.sendclickevent(True)
        e.setlinearlayoutparams(0)
        e.setmargin(8)
        e.setheight("WRAP_CONTENT")
        return e
    
    entries = []
    
    def setdir(d):
        global entries
        os.chdir(d)
        tree.clearchildren()
        entries = []
        entries.append(centry(".."))
        for f in os.listdir():
            entries.append(centry(f))
    setdir(args.dir)
    
    for ev in c.events():
        if ev == None:
            break
        if ev.type == tg.Event.destroy and ev.value["finishing"] == True:
            if args.folder:
                print(".")
            if args.file:
                sys.exit(1)
            sys.exit(0)
        if args.folder and ev.type == tg.Event.click and ev.id == navbutton:
            print(os.getcwd())
            sys.exit(0)
        if ev.type == tg.Event.click:
            try:
                b = entries[entries.index(ev.id)]
                path = b.gettext()
                if os.path.isdir(path):
                    setdir(path)
                else:
                    if args.file:
                        print(os.getcwd()+"/"+path)
                        sys.exit(0)
                    if not args.file and not args.folder:
                        if os.access(os.getcwd()+"/"+path, os.X_OK):
                            os.execl(os.getcwd()+"/"+path, path)
            except ValueError:
                pass
