import gzip
import base64
import os
import ntpath
from pathlib import Path
directory = 'src'
tmpFile = 'tmp.js'

os.system('espruino -p /dev/tty.usbserial-1410 -b 115200 --board ESP8266_4MB.json -e \'require("NumberFS").clear();digitalWrite(2,0);\'');

pathlist = Path(directory).glob('**/*.*')
for path in pathlist:
    # because path is object not string
    if ntpath.basename(path)[:1] != ".":
        print('\n*******\n'+str(path)[len(directory):])
        try:
          print(bytes(open(str(path)).read(),'utf-8'))
          #print(gzip.decompress(gzip.compress(bytes(open(str(path)).read(),'utf-8'))))
          os.system('espruino -p /dev/tty.usbserial-1410 -b 115200 --board ESP8266_4MB.json -e \'require("NumberFS").write("{}", `{}`);\''.format(str(path)[len(directory):], bytes(open(str(path)).read(),'utf-8').decode('UTF-8')));
        except:
          file_data = str(base64.b64encode(open(str(path), 'rb').read()))[2:][:-1]
          print(len(file_data))
          #if os.path.isfile(tmpFile):
            #  os.remove(tmpFile);
          #f = open(tmpFile, "a")
          block_size = 1024
          for i in range(0, len(file_data), block_size):
              print("file progress: {}/{}".format(str(i),str(len(file_data))))
              os.system('espruino -p /dev/tty.usbserial-1410 -b 115200 --board ESP8266_4MB.json -e \'require("NumberFS").write("{}", `{}`,{},{});\''.format(str(path)[len(directory):], file_data[i:][:block_size], str(i),str(len(file_data))));
              #f.write('require("NumberFS").write("' + str(path)[len(directory):] + '", "' + file_data[i:][:block_size] + '",' + str(i) + ', ' + str(len(file_data)) + ');\n\n')
          #f.close()
          #os.system('espruino -p /dev/tty.usbserial-1410 -b 115200 --board ESP8266_4MB.json ' + tmpFile);
          #os.remove(tmpFile);

os.system('espruino -p /dev/tty.usbserial-1410 -b 115200 --board ESP8266_4MB.json -e \'digitalWrite(2,1);\'');
# clear old nfs
#os.system('ls')

# save into nfs
