import uos , network , usocket
from time import sleep_ms
def exists(f):
    try:
      return uos.stat(f)[0] == 32768
    except:
      return False
def wget(ifile,ow=False): #Method to pull support files from git.microide.com
  print("Getting '{}'".format(ifile))
  if ow or not exists(ifile): #Overwrite Protection
    print("Connecting...")
    while not network.WLAN(network.STA_IF).isconnected():
      sleep_ms(10) #Wait on Network
    addr = usocket.getaddrinfo('dl.microIDE.com', 80)[0][-1]
    s = usocket.socket()
    s.connect(addr)
    s.send(bytes('GET /%s HTTP/1.0\r\nHost: dl.microIDE.com\r\n\r\n' % ifile, 'utf8'))
    data=s.readline()
    while not '200 OK' in data:
      data=s.readline()
    print("200 OK")
    while data != b'\r\n': #Strip the Header
      data=s.readline()
    #Dump the rest into a file
    f=open(ifile,'w')
    sleep_ms(10)
    while True:
      data = s.recv(4096)
      sleep_ms(10)
      if data:
        f.write(data)
      else:
        break
    print("Write Complete")
    f.close()
    s.close()
# import files seperatly to save RAM when executing
wget("microIDE.py",ow=True)
# These are all static files for the browser
wget("ace.js.gz",ow=True)
wget("microIDE.js.gz",ow=True)
wget("microIDE.css.gz",ow=True)
wget("microIDE.html.gz",ow=True)
wget("mode-python.js.gz",ow=True)
#wget("main.py",ow=False)  # Sample main.py

#Put this line in Boot to start microIDE
from microIDE import wget , epoch ,millis
