#!/usr/bin/env python3
import cv2
import math
import numpy as np
from pwnlib import tubes
import time

def solve(rawdat):
    data = []
    for line in rawdat.strip().split('\n'):
        data.append([int(x) for x in line.split(',')])

    x = np.array(data, dtype='uint8').T

    im = x # cv2.imread("output.png", cv2.IMREAD_GRAYSCALE)
    ret, thresh = cv2.threshold(im.copy(), 127, 255, 0)
    kernel = np.ones((5, 5), np.uint8)
    dilated = cv2.dilate(thresh.copy(), kernel, iterations = 2)

    cnts, hier = cv2.findContours(dilated.copy(), \
                                  cv2.RETR_TREE, \
                                  cv2.CHAIN_APPROX_NONE)

    edit = thresh.copy()
    cv2.drawContours(edit, cnts, -1, (0, 255, 0), 3)

    solve = ''
    for c in cnts:
        M = cv2.moments(c)
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])

        solve += (str(cX) + "," + str(cY)+'\n')
    return solve

TICKET = 'THE_TICKET'
r = tubes.remote.remote('stars.satellitesabove.me', 5013)
r.recvline()
r.send(TICKET+'\n')
going = True
while going:
    rawdat = r.recvuntil('Enter', drop=True)
    time.sleep(0.5)
    r.clean()
    solution = solve(rawdat.decode())
    r.send(solution+'\n')
    time.sleep(0.1)
    if r.recvuntil('Left...\n') == b'0 Left...\n':
        time.sleep(0.1)
        print(r.clean())
