#!/usr/bin/python3

'''
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

import argparse
import subprocess
import sys
import os
import sox

parser = argparse.ArgumentParser(description='Script to batch convert multichannel audio recordings to Higher-order Ambisonic using SATIE.')

parser.add_argument('path', type=str, help='A path to a directory containing mono soundfiles.')

parser.add_argument('ambi_order', type=int, help='The Ambisonic order of the encoded B-format soundfile', choices=range(1, 6))

args = parser.parse_args()


# Check if the path argument is a directory
if os.path.isdir(args.path):
    directory = args.path
else:
    print('You must provide a valid path to a directory')
    sys.exit(1)

if args.ambi_order:
    order = str(args.ambi_order)


# Check if the files to convert are mono. The SC script won't work with stereo files.
is_stereo = False
file_count = 0
with os.scandir(directory) as dir:
    for entry in dir:
        if entry.is_file():
            file_count += 1
            if not entry.name.startswith('.') and os.path.splitext(entry)[-1].split('.')[1] in sox.file_info.VALID_FORMATS:
                if sox.file_info.channels(os.path.join(directory, entry)) != 1:
                    print(entry.name, 'is a multichannel  file. This script can only take mono file.')
                    is_stereo = True

if is_stereo == True:
    print('Aborting.')
    sys.exit(1)

if file_count != 31:
    print('Incorrect number of sound files in the directory. Found', file_count, 'but expected 31 files.')
    sys.exit(1)

os.system('clear')
print('Conversion in progress...')

# The actual command to launch SC script
p = subprocess.Popen(['sclang', 'satieNRT.scd', directory, order], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Will output SC log at the end of the conversion or when error
print(p.communicate()[0].decode('ascii'))
