# test code to check for filename, header, and update

import time
import os
import microcontroller
import board
import digitalio
import rtc
import neopixel
import storage
import sdcardio
import busio
from adafruit_pcf8523 import pcf8523
import displayio
import terminalio

def main():
    try:
        vfs, sdcard = initialize_sd_card_storage()
        storage.mount(vfs, "/sd")
        print("succesfully mounted vfs")
    except:
        print( "SD card fail: missing or full" )
        vfs = False
        sdcard = False

    with open( "/sd/test.txt", "w" ) as b:
        b.write( "line one with some other stuff\n" )
        b.write( "line two with additional things" )

    with open( "/sd/test.txt", "r" ) as c:
        line1 = c.readline().rstrip()
        line2 = c.readline().rstrip()
        print( "{}, {}".format(line1, line2 ))
    print("done reading file")

    finu = "1234567"

    with open( "/sd/test.txt", "w" ) as b:
        b.write( "throwaway\n" )
        b.write( finu )

    with open( "/sd/test.txt", "r" ) as c:
        line1 = c.readline().rstrip()
        line2 = c.readline().rstrip()
        if finu == line2:
            print( "same")
    print("done reading file")




def initialize_sd_card_storage( ):
    try:
        cs = board.SD_CS
        sd_card_spi = busio.SPI(board.SD_SCK, MOSI=board.SD_MOSI, MISO=board.SD_MISO)
        sdcard = sdcardio.SDCard(sd_card_spi, cs)
        vfs = storage.VfsFat(sdcard)
        print( "sdcardio success" )
    except( OSError, ValueError ) as err:
        print( "No SD card found, or card is full: {}".format(err) )
        vfs = False
        sdcard = False
        onboard_neopixel.fill( 255,0,0 )
    return vfs, sdcard

main()
