import uos
from flashbdev import bdev


def check_bootsec():
    buf = bytearray(bdev.ioctl(5, 0))  # 5 is SEC_SIZE
    bdev.readblocks(0, buf)
    empty = True
    for b in buf:
        if b != 0xFF:
            empty = False
            break
    if empty:
        return True
    fs_corrupted()


def fs_corrupted():
    import time, microIDE, network
    ap = network.WLAN(network.AP_IF)
    ap.active(True)
    ap.config(essid="MicroIDE", password="NoPassword")
    while 1:
      print(
          """\
The filesystem appears to be corrupted. If you had important data there, you
may want to make a flash snapshot to try to recover it. Otherwise, perform
factory reprogramming of MicroPython firmware (completely erase flash, followed
by firmware programming).
"""
      )
      time.sleep(3)


def setup():
    check_bootsec()
    print("Performing initial setup")
    uos.VfsLfs2.mkfs(bdev)
    vfs = uos.VfsLfs2(bdev)
    uos.mount(vfs, "/")
    with open("boot.py", "w") as f:
        f.write(
            """\
# This file is executed on every boot (including wake-boot from deepsleep)
# Avoid changing things in boot.py and use main.py instead.
# Errors in this file may lock you out
# Libraries that are needed in this script
import _thread , os
from time import sleep, ticks_ms


def wdog():
  from machine import WDT
  #watchdog - once the chip stops responding it will reset
  wdt = WDT(timeout=15000)  # enable it with a timeout of 30s
  while True:
    #feed the dog - so it won't bite (reset)
    wdt.feed()
    #Reset chip after 60 minutes
    if ticks_ms()>1800000:
      import machine
      machine.reset()
    sleep(1)
_thread.start_new_thread(wdog,())


def sync():
  #get time form API  -   http://worldtimeapi.org/
  import network , json, usocket, machine, time , gc
  while not network.WLAN(network.STA_IF).isconnected():
    time.sleep(1) #Wait on Network
  addr = usocket.getaddrinfo('worldtimeapi.org', 80)[0][-1]
  s = usocket.socket()
  s.connect(addr)
  s.send(bytes('GET /%s HTTP/1.0\r\nHost: worldtimeapi.org\r\n\r\n' % "/api/timezone/America/Edmonton", 'utf8'))
  data=s.readline()
  while not '200 OK' in data:
    data=s.readline()
    time.sleep_ms(10)
  while data != b'\r\n': #Strip the Header
    data=s.readline()
    time.sleep_ms(10)
  e=json.loads(s.recv(4096))["unixtime"]
  
  tm = time.localtime(e-946710000)
  tm = tm[0:3] + (0,) + tm[3:6] + (0,)
  machine.RTC().datetime(tm)
  s.close()
  gc.collect() #Free up resources used in sync
  print("Time Sync OK - {}".format(e))
_thread.start_new_thread(sync,())

def wifi():
  import network
  #AP Mode
  ap = network.WLAN(network.AP_IF)
  ap.active(True)
  ap.config(essid="MicroIDE", password="password")
  #uncomment next line to enforce pasword
  #ap.config(authmode=3)
  #Station Mode
  con = network.WLAN(network.STA_IF);
  con.active(True)
  #Endless loop
  while True:
    #Error proofing- errors dont stop wifi connection attempts
    try: 
      #SSID #0 --------------------------
      con.active(True)
      con.connect("SSID_0","SSID_0_PASSWORD") # connect with SSID & Password
      sleep(15)                           # wait 15 seconds
      print(con.ifconfig())               # dump information like IP address
      while con.isconnected():            # while connected wait 60s
        sleep(60)
    except:
      pass
    sleep(15) #
    try: 
      #SSID #1 --------------------------
      con.active(True)
      con.connect("SSID_1","SSID_1_PASSWORD") # connect with SSID & Password
      sleep(15)                           # wait 15 seconds
      print(con.ifconfig())               # dump information like IP address
      while con.isconnected():            # while connected wait 60s
        sleep(60)
    except:
      pass  
    sleep(15) #
    try:
      #SSID #2 --------------------------
      con.active(True)
      con.connect("SSID_2","SSID_2_PASSWORD") # connect with SSID & Password
      sleep(15)                           # wait 15 seconds
      print(con.ifconfig())               # dump information like IP address
      while con.isconnected():            # while connected wait 60s
        sleep(60)
    except:
      pass  
    sleep(15) #
      #SSID #3 --------------------------
      #SSID #4 --------------------------
      #SSID #5 --------------------------
      #SSID #6 --------------------------
      #SSID #7 --------------------------

_thread.start_new_thread(wifi,())

#Activate microIDE web editor on port 80 (http)
from microIDE import epoch, wget

#Dump reason for last reset of the chip
from machine import reset_cause
opt={  1:"PWRON_RESET",2:"HARD_RESET/WEB_RESET",3:"WDT_RESET",4:"DEEPSLEEP_RESET",5:"SOFT_RESET/KEY_RESET"}
try:
  print("Reset Reason #{} - {}".format(reset_cause(),opt[reset_cause()]))
except:
  print("Reset Reason Error")
  
#main.py will be exuted now...
"""
        )
    return vfs
