#!/usr/bin/env python
import pigpio
import time
import datetime
import asyncio
import os
from itertools import cycle

# 1. Hook up the screen and buttons
# * the screen should show the frequency we're at
# * read the buttons
# 2. Encoder
# * Change frequency in the scope of a given band
PTT_IS_ON:bool = False
FREQUENCY:float = float(430)
modulations = cycle(["./modulations/ssb.sh", "./modulations/fmrds.sh"])


# init GPIO
pi = pigpio.pi()
# button pin
pi.set_mode(10, pigpio.INPUT)
# modulation change pin(change this)
pi.set_mode(11)

async def run_command(*args):
    process = await asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
    print("Started: %s, pid=%s" % (args, process.pid), flush=True)



async def button_press(gpio:int, level):
    #  TODO: light an LED
    global PTT_IS_ON
    if(pi.read(gpio)!=0):
        PTT_IS_ON = True
    if(pi.read(gpio)==0):
        PTT_IS_ON = False
    await asyncio.sleep(.5)



async def frequency(gpio):
    # TODO write this function after hooking up the encoder

async def main(freq:float):
    # TODO change after figuring out the logic
    task_created = False
    
    print("Ready")
    while True:
        await button_press(gpio, level)
        if (PTT_IS_ON and not task_created):
                asyncio.create_task(run_command(MODULATION, str(freq)))
                task_created = True
        elif (task_created and not PTT_IS_ON):
            await asyncio.sleep(1)
            asyncio.create_task(run_command("./kill.sh"))
            task_created = False
        await asyncio.sleep(.5)


if __name__ == "__main__":
    try:
        asyncio.run(main("", 430))
    except KeyboardInterrupt:
        print("\n")