from pico2d import *
import game_framework

import choose_state

TIME_PER_ACTION = 0.3
ACTION_PER_TIME = 1.0 / TIME_PER_ACTION
FRAMES_PER_ACTION_W = 4
FRAMES_PER_ACTION_R = 8

MOUSE_STUCK, MOUSE_UNSTUCK = range(2)

key_event_table = {
}

class IdleState:

    @staticmethod
    def enter(sad, event):
        if choose_state.selected_character != 'happy':
            choose_state.selected_character = 'none'

    @staticmethod
    def exit(sad, event):
        pass

    @staticmethod
    def do(sad):
        sad.wait_frame = (sad.wait_frame + FRAMES_PER_ACTION_W * ACTION_PER_TIME * game_framework.frame_time) % FRAMES_PER_ACTION_W

    @staticmethod
    def draw(sad):
        sad.wait_image.clip_draw(int(sad.wait_frame)*300, 0, 300, 300, 650, 300)


class RunState:

    @staticmethod
    def enter(sad, event):
        if choose_state.selected_character != 'sad':
            choose_state.cursor.playSound()
        choose_state.selected_character = 'sad'

    @staticmethod
    def exit(sad, event):
        pass


    @staticmethod
    def do(sad):
        sad.run_frame = (sad.run_frame + FRAMES_PER_ACTION_R * ACTION_PER_TIME * game_framework.frame_time) % FRAMES_PER_ACTION_R

    @staticmethod
    def draw(sad):
        sad.run_image.clip_composite_draw(int(sad.run_frame)*100, 0, 100, 100, 0, '', 650, 300, 300, 300)




next_state_table = {
    IdleState: {MOUSE_STUCK: RunState, MOUSE_UNSTUCK: IdleState},
    RunState: {MOUSE_STUCK: RunState, MOUSE_UNSTUCK: IdleState}
}

class Choose_sadness300:
    run_image = None
    wait_image = None
    def __init__(self):
        self.run_frame = 0
        self.wait_frame = 0
        if self.run_image == None:
            self.run_image = load_image('resources\\run_sadness100.png')
        if self.wait_image == None:
            self.wait_image = load_image('resources\\wait_sadness300.png')
        self.event_que = []
        self.cur_state = IdleState
        self.cur_state.enter(self, None)

    def add_event(self, event):
        self.event_que.insert(0, event)

    def update(self):
        self.cur_state.do(self)
        if len(self.event_que) > 0:
            event = self.event_que.pop()
            self.cur_state.exit(self, event)
            self.cur_state = next_state_table[self.cur_state][event]
            self.cur_state.enter(self, event)

    def draw(self):
        self.cur_state.draw(self)

    def handle_event(self, event):
        if (event.type, event.key) in key_event_table:
            key_event = key_event_table[(event.type, event.key)]
            self.add_event(key_event)
        elif event.type == SDL_MOUSEMOTION:
            if 500 < event.x < 800 and 100 < (700 - 1 - event.y) < 450:
                self.add_event(MOUSE_STUCK)
            else:
                self.add_event(MOUSE_UNSTUCK)
