#####################################################
# @module    misc_utils.py                          #
# @brief     simple code snippits for misc tasks    #
# @author    Jamie Bird                             #
# @date      Sept 2020                              #
# @copyright Racelogic Ltd., 2020                   #
# @Version   1.0                                    #
#####################################################

import ft8xx as ft
import gui
from micropython import const

ORIENTATION_DEFAULT = const(6)
ORIENTATION_INVERTED = const(1)
ORIENTATION_PORTRAIT = const(1<<1)
ORIENTATION_MIRRORED = const(1<<2)

NO_TOUCH = const(0x8000)

CTOUCH_TAG0 = 0x30212C
CTOUCH_TAG1 = 0x302134
CTOUCH_TAG2 = 0x30213C
CTOUCH_TAG3 = 0x302144
CTOUCH_TAG4 = 0x30214C

def stop_sound():
    ft.wr32(ft.REG_PLAYBACK_LENGTH, 0)
    ft.wr8(ft.REG_PLAYBACK_PLAY, 1)

def disable_speaker():
    ft.wr16(ft.REG_GPIOX, 0x80)

def audio_playing():
    return ft.rd8(ft.REG_PLAY)

def set_orientation(*args):
    """NOTE: Does not rotate touch matrix!"""
    args = [op for op in args if op!= ORIENTATION_DEFAULT]
    d = ORIENTATION_DEFAULT
    for op in args:
        d ^= op
    ft.cpcmd_setrotate(d)

def current_tag():
    return ft.rd8(ft.REG_TOUCH_TAG)

def multi_touch_enabled(val=None):
    if val is None:
        return not bool(ft.rd8(ft.REG_CTOUCH_EXTENDED))
    else:
        ft.wr8(ft.REG_CTOUCH_EXTENDED, int(not bool(val)))

def active_presses():
    count = 0
    presses = []
    for press in (get_press_xy, get_press_2_xy, get_press_3_xy, get_press_4_xy, get_press_5_xy):
        presses.append(press())
        if any(presses[-1]):
            count +=1
    return count, presses


def get_press_xy():
    return ft.rd16(ft.REG_TOUCH_TAG_XY+2) & 0x7FF, ft.rd16(ft.REG_TOUCH_TAG_XY) & 0x7FF

def get_press_2_xy():
    return ft.rd16(ft.REG_CTOUCH_TOUCH1_XY+2) & 0x7FF, ft.rd16(ft.REG_CTOUCH_TOUCH1_XY) & 0x7FF

def get_press_3_xy():
    return ft.rd16(ft.REG_CTOUCH_TOUCH2_XY+2) & 0x7FF, ft.rd16(ft.REG_CTOUCH_TOUCH2_XY) & 0x7FF

def get_press_4_xy():
    return ft.rd16(ft.REG_CTOUCH_TOUCH3_XY+2) & 0x7FF, ft.rd16(ft.REG_CTOUCH_TOUCH3_XY) & 0x7FF

def get_press_5_xy():
    return ft.rd16(ft.REG_CTOUCH_TOUCH4_X) & 0x7FF, ft.rd16(ft.REG_CTOUCH_TOUCH4_Y) & 0x7FF

def press_2_tag():
    return ft.rd8(CTOUCH_TAG1)

def press_3_tag():
    return ft.rd8(CTOUCH_TAG2)

def press_4_tag():
    return ft.rd8(CTOUCH_TAG3)

def press_5_tag():
    return ft.rd8(CTOUCH_TAG4)


def run_file(file_name):
    with open(file_name) as f:
        file = f.read()
    exec(file)





