#!/usr/bin/env python3
import os
import time
from itertools import count
from strategy import State, moves_to_keys
from interaction import get_exapunks_window, focus_window, \
                        screenshot_board, press_keys, listen_keys


def save_screenshot(win):
    board = screenshot_board(win).convert('RGB')
    os.makedirs('screens', exist_ok=True)
    for i in count(1):
        path = 'screens/board%d.png' % i
        if not os.path.exists(path):
            print('save screenshot in', path)
            board.save(path)
            break


if __name__ == '__main__':
    win = get_exapunks_window()
    focus_window(win)

    listen_keys({'s': lambda: save_screenshot(win)})

    prev_score = None

    while True:
        board = screenshot_board(win)

        try:
            state = State.detect(board)
        except (TypeError, AssertionError):
            print('error during parsing, wait for a bit')
            time.sleep(.1)
            continue

        print('\033c', end='')
        print('parsed:')
        state.print()
        print()

        start = time.time()
        moves = state.solve()
        end = time.time()
        print('thought for %.4f seconds' % (end - start))

        if moves:
            print('moves:', moves_to_keys(moves))
            points, newstate = state.simulate(moves)
            score = newstate.score(points, moves, state)
            print('     score:', score)
            print('prev score:', prev_score)
            print()
            prev_score = score

            print('target after moves:')
            newstate.print()
            print()

            press_keys(win, moves_to_keys(moves))
        else:
            print('no moves')
