
import curses
import time

FPS = 15    
FRAME_TIME = 1.0 / FPS


def getCh(stdscr):
    keys = []
    ch = ' '
    while ch != None and ch !=-1:
        try:
            ch = stdscr.getch()
            keys.append(ch)
        except:
            pass
    return keys

def getMouse(ch):
    clicks = []
    if curses.KEY_MOUSE in ch:
        try:
            _, mx, my, _, bstate = curses.getmouse()
            clicks.append((my,mx))
        except curses.error:
            pass
    return clicks

def wait(start,fps=FPS):
    frame_time = 1.0/fps
    if not start:
        return
    elapsed = time.time() - start
    if elapsed < frame_time:
        time.sleep(frame_time - elapsed)
    return time.time()

def prnt(stdscr,y,x,txt):
    h,w = stdscr.getmaxyx()
    for line in txt.split('\n'):
        if y >= h:
            return
        e = min(len(line), w-x )
        try:
            stdscr.addstr(y,x,line[:e])
        except:
            pass
        y = y + 1


def satellite(stdscr,txt,y,x):
    h,w = stdscr.getmaxyx()
    mp = txt.split('\n')
    for cy in range(h):
        if cy >= len(mp):
            continue
        for cx in range(w):
            if cx >= len(mp[cy+y]):
                continue
            c = mp[cy+y][cx+x]
            try:
                stdscr.addstr(y,x,c)
            except:
                pass


def button(stdscr,clicked,y,x,txt=[]):
    if not x or not y:
        return False
    h,w = stdscr.getmaxyx()
    for line in txt:
        cx = x
        for cell in line:
            if cell != '.' and cx < w and y < h:
                try:
                    stdscr.addstr(y,cx,cell)
                    if (y,cx) in clicked:
                        return True
                except:
                    pass
            cx = cx + 1
        y = y + 1
    return False

def gtfo(stdscr,keys,clicks,y,x):
    if ord('q') in keys:
        return True
    if ord('x') in keys:
        return True
    if ord('Q') in keys:
        return True
    if ord('X') in keys:
        return True
    if 27 in keys:
        return True
    btn = [
        "┏━━━━━━┓",
        "┃[Q]uit┃",
        "┃ or   ┃",
        "┃E[x]it┃",
        "┗━━━━━━┛",
            ]
    if button(stdscr,clicks,y,x,btn):
        return True
    return False

def anykey(stdscr,keys):
    stdscr.addstr(1, 10, "anykey to continue")
    if curses.KEY_MOUSE in keys:
        return True
    for key in keys:
        if key < 0:
            continue
        return True
    return False


def getNpt(stdscr):
    keys = getCh(stdscr)
    clicks = getMouse(keys)
    return keys,clicks

