# Copyright 3D Control Systems, Inc. All Rights Reserved 2017-2019.
# Built in San Francisco.

# This software is distributed under a commercial license for personal,
# educational, corporate or any other use.
# The software as a whole or any parts of it is prohibited for distribution or
# use without obtaining a license from 3D Control Systems, Inc.

# All software licenses are subject to the 3DPrinterOS terms of use
# (available at https://www.3dprinteros.com/terms-and-conditions/),
# and privacy policy (available at https://www.3dprinteros.com/privacy-policy/)

import os
import subprocess
import logging

import config
import paths


DEFAULT_VOLUME_PERCENT = 50


def play(audio_file, blocking=True, in_audio_files_folder=True, volume_mult=1.0, abs_volume_percent=0):
    if in_audio_files_folder:
        path = os.path.abspath(os.path.join(paths.AUDIO_FILES_FOLDER, audio_file))
    else:
        path = audio_file
    if os.path.exists(path):
        if abs_volume_percent:
            volume = abs_volume_percent
        else:
            volume = config.get_settings().get('audio_volume', DEFAULT_VOLUME_PERCENT) * volume_mult
        try:
            proc = subprocess.Popen(['ffplay', '-autoexit', "-volume", str(int(volume)), path])
            logging.getLogger('__name__').info(f'Playing audio file: {path}')
            if blocking:
                proc.wait()
        except subprocess.SubprocessError as e:
            logging.getLogger('__name__').error(f'Error playing audio file: {path}')
    else:
        raise FileNotFoundError('Unable to find a file to play:' + str(path))

if __name__ == "__main__":
    play('test.ogg', blocking=False, volume_mult=0.6)
