#!/usr/bin/python3
# -*- coding: utf-8 -*-

""" MIT License

Copyright (c) 2018 Martin Villalba

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import argparse
import pygame
import pyaudio
import sys
from pydub import AudioSegment
from pydub.utils import make_chunks

parser = argparse.ArgumentParser(description="Simulate a storm on screen")
parser.add_argument("filename",
        help="play this rain MP3 file")
parser.add_argument("-l", "--loop", type=int, nargs='?', metavar="loop", default=0,
        help="replay the audio n times (default: 0)")

args = parser.parse_args()

# Initialize audio
print("Initializing audio...")
sound = AudioSegment.from_file(args.filename)
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(sound.sample_width),
                channels=sound.channels,
                rate=sound.frame_rate,
                output=True)

# Some audio variables that might come useful
start = 0
length = sound.duration_seconds
volume = 100
playchunk = sound[start*1000.0:(start+length)*1000.0] - (60-(60*(volume/100.0)))
millisecondchunk = 50/1000.0

# Calculate the maximum RMS, to calibrate volume (and lightning threshold)
print("Calculating audio levels...")
max_rms=0
for chunks in make_chunks(playchunk, millisecondchunk*1000):
    if chunks.rms > max_rms:
        max_rms = chunks.rms

# Initialize video
pygame.init()
screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
running = True
old_val=0

for _ in range(args.loop + 1):
    for chunks in make_chunks(playchunk, millisecondchunk*1000):
        # Play this chunk
        stream.write(chunks._data)

        # Normalize the RMS value, and remove all values below 0.4
        # For the remaining values, scale them in the range 0-255
        val = chunks.rms/max_rms
        if val<0.2:
            val=0
        val = val*255
        # If the value has changed, flip the screen
        # (saves useless flipping)
        if(val != old_val):
            old_val = val
            screen.fill((val,val,val))
            pygame.display.flip()
        # Checks whether we should exit the program
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q or event.key == pygame.K_ESCAPE:
                    running = False
        if not running:
            break

# Closes all resources
stream.stop_stream()
stream.close()
p.terminate()
