import os
import sys
import time

import allegory_base
from owanimo.app.error import ERROR as e

from owanimo.util import define
from owanimo.util.log import LOG as L


class Allegory(allegory_base.AllegoryBase):
    def __init__(self, runner, profile, player):
        allegory_base.AllegoryBase.__init__(self, runner, profile, player)
        self.adb().connect()

    def get_reference(self, reference):
        return os.path.join(define.APP_TMP,
            self.adb().get().PATTERN_MATCH_PATH, reference)

    def get_target(self, target):
        return os.path.join(define.APP_TMP, target)

    def capture(self, filename=None):
        if filename ==None: filename = "capture.png"
        self.adb().snapshot(filename, define.APP_TMP)

    def enable(self, reference, target=None):
        L.debug("reference : %s " % reference)
        if target == None:
            self.adb().snapshot(self.adb().get().TMP_PICTURE, define.APP_TMP)
            target = self.adb().get().TMP_PICTURE
        return self.pic().is_pattern(
            self.get_target(target), self.get_reference(reference))

    def tap(self, reference, target=None):
        L.debug("reference : %s " % reference)
        if target == None:
            self.adb().snapshot(self.adb().get().TMP_PICTURE, define.APP_TMP)
            target = self.adb().get().TMP_PICTURE
        result = self.pic().find_pattern(
            self.get_target(target), self.get_reference(reference))
        if not result == None:
            self.adb().tap(result.x + (result.width / 2), result.y + (result.height / 2))
            return True
        else:
            return False

    def _tap(self, x, y):
        self.adb().tap(x, y)

    def swipe(self, xarray, yarray):
        self.adb().swipe(xarray, yarray)

    def start(self):
        self.adb().invoke(self.adb().get().APP_PUYOQUEST)

    def stop(self):
        self.adb().stop(self.adb().get().APP_PUYOQUEST)

if __name__ == '__main__':
    a = Allegory()
    b.login()
    b.present()
    b.capture()
    time.sleep(5)
    b.stop()
