##
# @file    main.py
# @brief   Example of record from microphone and play through speaker
# @version 1.0
#

import ft8xx as ft
import gui
from ustruct import unpack_from
import vts

def play(b):
    avg = 0
    for i in range(len(b)):
        x = unpack_from('b', b, i)[0]
        avg += x
    avg = int(avg / len(b))
    print(avg)
    for i in range(len(b)):
        b[i] = 2 * (unpack_from('b', b, i)[0] - avg)

    len_graph = 800
    mv = memoryview(b)
    gmax = 1000000
    gmin = gmax + len_graph
    k = len(mv) // len_graph
    i = 0
    ft.mutex_take(True)
    while i < len_graph:
        s = unpack_from('b'*k, mv, i * k)
        ft.wr8(ft.RAM_G + gmax + i, 128 - max(s))
        ft.wr8(ft.RAM_G + gmin + i, 128 - min(s))
        i += 1
    ft.mutex_give()

    x = 0
    y = 112
    w = 256
    gui_l = [
        [gui.PARAM_CLRCOLOR, gui.DL_COLOR_RGB(0,0,0)]
    ]
    while x < len_graph:
        gui_l.append([
            gui.DL_COLOR_RGB(255,0,0),
            gui.DL_COLOR_A(255),
            gui.DL_BITMAP_SOURCE(ft.RAM_G + gmax + x),
            gui.DL_BITMAP_LAYOUT(ft.BMPLAYOUT_BARGRAPH, 256, 1),
            gui.DL_BITMAP_SIZE(0, 0, 0, w, 256),
            gui.DL_BEGIN(gui.PRIM_BITMAPS),
            gui.DL_VERTEX2F(x, y),
            gui.DL_END()
        ])
        gui_l.append([
            gui.DL_COLOR_RGB(0,0,0),
            gui.DL_COLOR_A(224),
            gui.DL_BITMAP_SOURCE(ft.RAM_G + gmin + x),
            gui.DL_BITMAP_LAYOUT(ft.BMPLAYOUT_BARGRAPH, 256, 1),
            gui.DL_BITMAP_SIZE(0, 0, 0, w, 256),
            gui.DL_BEGIN(gui.PRIM_BITMAPS),
            gui.DL_VERTEX2F(x, y),
            gui.DL_END()
        ])
        x += 256
        w = 256 if x < (len_graph - 256) else len_graph - x
    gui.show(gui_l)

    print('Uploading...')
    ft.wrbuf(ft.RAM_G, b)
    ft.wr32(ft.REG_PLAYBACK_START, ft.RAM_G)
    ft.wr32(ft.REG_PLAYBACK_LENGTH, len(b))
    ft.wr32(ft.REG_PLAYBACK_FREQ, 16000)
    ft.wr32(ft.REG_PLAYBACK_FORMAT, 0)
    ft.wr32(ft.REG_PLAYBACK_LOOP, 0)
    ft.wr32(ft.REG_VOL_PB, 255)
    ft.wr32(ft.REG_PLAYBACK_PLAY, 1)

b = bytearray(16000 * 10)
vts.record(b, 2)
print('Recording finished.')
play(b)
