__author__ = 'butzel'
__license__ = "GPLv3: https://www.gnu.org/licenses/gpl-3.0.txt"


def info():
    print("""This little function-collection can help with simple file operations
function ^  arguments  ^ description
 cat     | fname,pprint   | reads file ''fname'', ''pprint''=1=print;=2=lineno?
 cd      | dname          | change directory to ''dname'' (relative & absolute)
 cp      | old,new        | copy the ''old''-file to ''new''
 deltree | dname          | deletes a subdirectory recursively
 df      | dname          | shows free diskspace of fs behind ''dname''-dir
 info    |                | this text
 ls      | dname          | list files and dirs in the directory ''dname''
 dir     | dname          | pretty list files & dirs in the directory ''dname''
 mem     | free           | prints free heap, free = run GC
 mkdir   | dname          | creates a the directory named ''dname''
 mv      | old,new        | moves file from ''old'' to ''new''
 reset   |                | machine.reset()
 rm      | fname          | removes file or dir with name ''fname''
 pwd     |                | print working directory
 save    | fname,data,app | save ''data'' to file ''fname''. ''app'' = append?
 speed   | freq           | returns or set the cpu speed (freq is optional)
 :: WLAN
 rfkill  | enable         | enable/disable WLan
 wconn   | essid,password | connect to essid & use password
 wscan   |                | list all available wlan ssids
 ifconfig| pprint         | print interface config, pprint = print it?
 wlanap  | essid,psk,chan | open a WLAN-AP essid=name psk=WPA2-Passwd chan=nel
 :: I²C
 i2cscan | scl,sda        | scan I2C-Bus (with Clock=scl, Data=sda) for devices
 i2cwrite| scl,sda,adr,dta| write dta to device adr on I2C-Bus (scl, sda)
 i2cread | scl,sda,adr,len| read len bytes from device 'adr' on I2C-Bus  
Version 20220403""")


def reset():
    __import__("machine").reset()


def cat(fname, pprint=0):
    x = open(fname)
    fname = x.read()
    x.close()
    if pprint:
        pprint = int(pprint)
        if pprint > 1:
            cnt = 0
            for i in fname.split("\n"):
                cnt = cnt + 1
                print(cnt, ":", i)
        else:
            print(fname)
    else:
        return fname


def save(fname, data, append=0):
    if append:
        fh = open(fname, "a")
    else:
        fh = open(fname, "w")
    data = fh.write(data)
    fh.flush()
    fh.close()
    return data


def mkdir(dname):
    return __import__("os").mkdir(dname)


def ls(dname=""):
    retval = ""
    try:
        for i in __import__("os").ilistdir(dname):
            if i[1] == 0x8000:
                retval += "f[" + flen(dname + "/" + i[0]) + "byte ]\t "
                retval += i[0] + "\n"
            else:
                print("hey")
                retval += "d["
                retval += len(__import__("uos").listdir(dname
                                                        + "/" + i[0]))
                retval += "files]\t ", i[0] + "\n"
    except:
        for i in __import__("os").listdir(dname):
            retval += str(i) + "\n"
            # print(i)
    return retval.strip()


def ll(dname=""):
    print(ls(dname))


def flen(fname):
    x = open(fname, "r")
    fname = x.seek(__import__("flashbdev").size)
    x.close()
    return fname


def cd(dname):
    __import__("os").chdir(dname)


def rm(fname):
    try:
        __import__("os").remove(fname)
    except:
        __import__("os").rmdir(fname)


def deltree(fname):
    cd(fname)
    for i in __import__("os").listdir():
        if __import__("os").stat(i)[0] == 16384:
            deltree(i)
        else:
            rm(i)
    cd("..")
    rm(fname)


def pwd():
    return __import__("os").getcwd()


def mv(old, new):
    __import__("os").rename(old, new)


def cp(old, new):
    n = open(new, "w")
    n.write(cat(old))
    n.flush()
    n.close()


def df(dname=None):
    if dname is None:
        dname = pwd()
    print("diskfree for:", dname, end=" ")
    if 'statvfs' in dir(__import__("os")):
        x = __import__("os").statvfs(dname)
    else:
        # PyCom
        x = __import__("os").stat(dname)
    try:
        print("flash-size: ", __import__("flashbdev").size, "byte")
    except:
        try:
            # PyCom
            print(" os.getfree: ", __import__("os").getfree(dname), "Kbytes")
        except:
            pass
    print("  \t(blocksize: %u bytes)" % (x[0],))
    print(" disk size:\t%4u blocks\t%8u bytes" % (x[2], (x[2] * x[1])))
    print(" disk free:\t%4u blocks\t%8u bytes" % (x[4], (x[4] * x[0])))
    print(" disk used:\t%4u blocks\t%8u bytes" % (x[2]-x[3], (x[0] * (x[2] - x[3]))))
    return x


def mem(free=False):
    if free:
        free = __import__("gc").isenabled()
        __import__("gc").disable()
        __import__("gc").collect()
        if free:
            __import__("gc").enable()
    __import__("micropython").mem_info()
    return __import__("gc").mem_free()


def turbo(on=True):
    __import__("machine").freq(16 * 10**7 if on else 8*10**7)


def speed(speed=0):
    speed = int(speed)
    if speed > 0:
        return __import__("machine").freq(speed)
    return __import__("machine").freq()


def sha256(fname):
    def hexdigest(fname):
        t = "0.1.2.3.4.5.6.7.8.9.A.B.C.D.E.F".split('.')
        return "".join([t[i // 16] + t[i % 16] for i in fname])
    retval = __import__("uhashlib").sha256()
    with open(fname, "rb") as fname:
        data = fname.read(1024)
        while data:
            retval.update(data)
            data = fname.read(1024)
    return hexdigest(retval.digest())
# -- snip -- head -n 186 >> fs2.py


def rfkill(enable=False):
    __import__("network").WLAN().active(enable)


def wscan(pprint=0):
    old = __import__("network").WLAN().active()
    __import__("network").WLAN().active(True)
    retval = __import__("network").WLAN().scan()
    if pprint:
        for w in retval:
            print(w[0].decode())
            if pprint > 1:
                authinfo = ["open", "WEP", "WPA", "WPA2", "WPA/WPA2"]
                print(" '-> Channel", w[2])
                print(" '-> Auth   ", authinfo[w[4]])
            if pprint > 2:
                print(" '-> BSSID  ", w[1])
                print(" '-> RSSI   ", w[3])
                print(" '->", "visible" if w[5] else "hidden")
            if pprint > 1:
                print()
    __import__("network").WLAN().active(old)
    return retval


def wconn(ssid=None, pwd=None):
    __import__("network").WLAN().active(True)
    if ssid is None:
        ssid = wscan(1)
        ssid = input("Enter SSID: ")
    if pwd is None:
        pwd = input("Password: ")
    __import__("network").WLAN().connect(ssid, pwd)


def ifconfig(pprint=0):
    retval = __import__("network").WLAN().ifconfig()
    if pprint:
        print("IPv4:   ", retval[0])
        print("netmask:", retval[1])
        print("Gateway:", retval[2])
        print("DNS:    ", retval[3])
    return retval


def wlanap(ssid, psk=None, channel=1):
    channel = int(channel)
    retval = __import__("network").WLAN(__import__("network").AP_IF)
    if psk:
        retval.config(password=psk)
        retval.config(authmode=__import__("network").AUTH_WPA2_PSK)
    retval.config(essid=ssid, channel=channel, hidden=False)
    retval.active(True)
    return retval


def i2cscan(scl, sda, lst=False):
    retval = []
    i2c = _i2c_(scl, sda)
    for dev in i2c.scan():
        if lst: print(hex(dev))
        retval.append(dev)
    return retval

def i2cread(scl, sda, adr=0, sz=1):
    i2c = _i2c_(scl, sda)
    if type(sz) == str: sz = int(sz)
    if type(adr) == str: adr = int(adr)
    if adr == 0: adr = i2c.scan()[0]
    return i2c.readfrom(adr, sz)

def i2cwrite(scl, sda, adr, data):
    i2c = _i2c_(scl, sda)
    if type(adr) == str: adr = int(adr)
    if adr == 0: adr = i2c.scan()[0]
    return i2c.writeto(adr, data)

def _i2c_(scl, sda):
    if type(scl) == str: scl = int(scl)
    if type(sda) == str: sda = int(sda)
    if type(scl) == int: scl = __import__("machine").Pin(scl)
    if type(sda) == int: sda = __import__("machine").Pin(sda)
    return __import__("machine").SoftI2C(scl=scl, sda=sda)

# -- snip -- head -n 266 >> fs_no_shell.py


def sh():
    def __call__(x, ln):
        try:
            x = x(*ln) if ln else x()
        except Exception as ln:
            x = "Error #" + str(ln.errno) + ":\n" + str(ln.value)
        return x

    def __gc__():
        x = __import__("gc").isenabled()
        __import__("gc").disable()
        __import__("gc").collect()
        if x:
            __import__("gc").enable()

    loop = True
    alias = {"help": "info"}
    asvar = ""
    x = None
    while loop:
        prompt = __import__("os").getcwd() + " #"
        asvar = ""
        glob = globals()
        # Input
        ln = input(prompt).strip().split(" ")
        while ' ' in ln:
            ln.remove(' ')

        # Define Vars
        if '=' in ln[0]:
            asvar = ln[0].split("=")
            ln[0] = asvar[1]
            asvar = asvar[0]

        for i in range(len(ln)):
            if ln[i].startswith("$"):
                x = ln[i][1:]
                if x in glob:
                    ln[i] = glob[x]
                else:
                    ln[i] = ""

        if ln[0] in alias:
            ln[0] = alias[ln[0]]

        # command-loop
        if ln[0] == 'exit':
            loop = False

        elif ln[0] + '.py' in __import__("os").listdir():
            __gc__()
            with open(ln[0] + ".py", "r") as x:
                ln = x.read()
            __gc__()
            exec(ln)

        elif ln[0] in glob:
            x = glob[ln[0]]
            if x.__class__.__name__ == 'function':
                x = __call__(x, ln[1:])
            if x and asvar:
                exec(asvar + "= '" + x.replace("\n", '\\n') + "'")
            elif x:
                print(x)

        elif ln[0] == '#':
            x = ""
            for i in ln[1:]:
                x += i + " "
            try:
                x = (eval(x))
                if x and asvar:
                    exec(asvar + "=" + x)
                elif x:
                    print(x)
            except Exception as e:
                print("#:" + str(e.errno) + ":" + e.value)
        elif ln[0] == "echo":
            print(ln[1:])
        elif asvar:
            exec(asvar + "= '" + ln[0] + "'")
        else:
            print("Command not found")
