#!/usr/bin/env python3
import sys
import wave

import pyaudio


def record_audio(seconds: int, filename: str) -> None:
    oformat = pyaudio.paInt16
    channels = 2
    rate = 44100
    chunk = 1024
    record_seconds = int(seconds)
    wave_output_filename = f"{filename}.wav"

    audio = pyaudio.PyAudio()

    # start Recording
    stream = audio.open(
        format=oformat,
        channels=channels,
        rate=rate,
        input=True,
        frames_per_buffer=chunk,
    )
    print(f"recording for {seconds} seconds ...")
    frames = []
    for i in range(0, int(rate / chunk * record_seconds)):
        data = stream.read(chunk)
        frames.append(data)

        s = i / (rate / chunk)
        if s % 1 < 0.025:
            if int(seconds - s) < 11:
                print(int(seconds - s) + 1, ' sec left')

    print(f"recording saved to {wave_output_filename}")

    # stop Recording
    stream.stop_stream()
    stream.close()
    audio.terminate()

    waveFile = wave.open(wave_output_filename, "wb")
    waveFile.setnchannels(channels)
    waveFile.setsampwidth(audio.get_sample_size(oformat))
    waveFile.setframerate(rate)
    waveFile.writeframes(b"".join(frames))
    waveFile.close()


if __name__ == '__main__':
    args = sys.argv
    sec = args[1] if args[1:] else 15
    name = args[2] if args[2:] else 'recording'
    record_audio(int(sec), name)
