"""Simple program to demo how to use meshtastic library.
   To run: python examples/info.py
"""

import meshtastic
import meshtastic.serial_interface
import json
import base64
import os
from gi.repository import GLib

import meshtastic.ble_interface

#meshtastic_config_dir = GLib.get_user_config_dir() + '/gtk_meshtastic_client'
meshtastic_config_dir = GLib.get_tmp_dir()
bluetooth_scanned_device_path = meshtastic_config_dir + '/bluetooth.json'
print("Save file: " + str(bluetooth_scanned_device_path))

if os.path.exists(bluetooth_scanned_device_path):
    with open(bluetooth_scanned_device_path, 'r+') as json_file:
        content = json_file.read().strip()
        if content:
            try:
                data = json.loads(content)
            except:
                os.remove(bluetooth_scanned_device_path)
            else:
                for i in data:
                    print("name: " + str(i["name"]))
                    print("adddress: " + str(i["address"]))

                exit()

print("Scanning takes 10 seconds")
device_list =  meshtastic.ble_interface.BLEInterface.scan()

device_json_string = '[\n'

for x in device_list:
    device_json_string = (device_json_string + " {\"name\": \""+ str(x.name) + "\", \"address\": \"" + str(x.address) + "\"},")

device_json_string = device_json_string[:-1]

device_json_string = (device_json_string + "\n]")

if not os.path.exists(meshtastic_config_dir):
    os.makedirs(meshtastic_config_dir)

with open(bluetooth_scanned_device_path, 'w') as json_file:
    json_file.write(device_json_string)

json_file.close()
