#!/usr/bin/env python3

import sys
import os
import time
import random
import socket
import pygame

from pygame.locals import *

os.environ["SDL_VIDEODRIVER"] = "dummy"

# "we'll fix it in post!"
MAPPING = [
    8,
    7,
    6,
    5,
    1,
    2,
    3,
    4,
    9,
    10,
    11,
    0
]

SPATH = "sounds/"

play_again_at = time.time()

def logmesohard(name):
    s = socket.socket()
    s.connect(('10.8.1.1', 2023))
    s.sendall('hackerspace.soundboard.{} 1 {}\n'.format(name.replace('.', '_'), int(time.time())))
    s.close()

    print("Playing {}".format(name))

class Sound(object):
    def __init__(self, paths):
        self.paths = paths
    def create(self):
        print("Loading {}".format(", ".join(self.paths)))
        self.sounds = [(pygame.mixer.Sound(SPATH + p), p) for p in self.paths]

class SimpleSound(Sound):
    def __init__(self, path):
        super(SimpleSound, self).__init__([path,])

    def play(self):
        logmesohard(self.paths[0])
        # loonquawl is an idiot
        sound = self.sounds[0][0]
        sound.play()
        return sound.get_length() * 0.5

class RandomSound(Sound):
    def play(self):
        s, path = random.choice(self.sounds)
        logmesohard(self.path)
        print(s)
        s.play()
        return s.get_length() * 0.5

class ListSound(Sound):
    def __init__(self, paths):
        self._state = self._getsound()
        super(ListSound, self).__init__(paths)

    def _getsound(self):
        last_sound = None
        delay = 3
        index = 0
        while True:
            if last_sound is None or last_sound + delay < time.time():
                index = 0
                last_sound = time.time()
            else:
                index += 1
                if index >= len(self.sounds):
                    index = 0
                last_sound = time.time()
            sound = self.sounds[index]
            yield sound[0], sound[1]

    def play(self):
        s, path = next(self._state)
        print(s)
        s.play()
        return s.get_length() * 0.75

SOUNDS = [
    SimpleSound("nope.wav"),
    SimpleSound("yesyes.wav"),
    SimpleSound("ba-dum-tish.wav"),
    SimpleSound("crickets.wav"),
    SimpleSound("wind.wav"),
    SimpleSound("trombone.wav"),
    RandomSound(["whip.wav", "whip2.wav", "whip4.wav"]),
    SimpleSound("finishim.wav"),
#   SimpleSound("wtfboom.wav"), # We all hate it anyway.
    ListSound(["dayum1.wav", "dayum2.wav", "dayum3.wav"]),
    SimpleSound("noooooooo.wav"),
    SimpleSound("fanfare.wav"),
    SimpleSound("dundundun.wav"),
]

if __name__ == "__main__":
    # are we a fucking rpi?
    f = open("/proc/cpuinfo", "r")
    d = f.read()
    f.close()
    if "BCM2708" in d:
        print("We are on an rpi. Doing ALSA hack.")
        os.system("amixer cset numid=3 1")

    pygame.mixer.init()
    pygame.display.init()
    pygame.display.set_mode((1,1))
    for s in SOUNDS:
        s.create()
    pygame.joystick.init()

    if pygame.joystick.get_count() == 0:
        print("You don't have any joysticks.")
        exit()

    j = pygame.joystick.Joystick(0)
    j.init()
    print("Ready!")

    while True:
        pygame.event.pump()
        for event in pygame.event.get():
            if event.type == JOYBUTTONDOWN:
                print("JOYBUTTONDOWN")
                n = MAPPING.index(event.button)
                if n < len(SOUNDS) and time.time() >= play_again_at:
                    play_again_at = time.time() + SOUNDS[n].play()

        time.sleep(0.01)

