#!/usr/bin/python3

# audio-offset-finder
#
# Copyright (c) 2014-22 British Broadcasting Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from audio_offset_finder.audio_offset_finder import find_offset
import argparse
import sys


def main(argv):
    parser = argparse.ArgumentParser(
        description="Find the offset of an audio file within another one",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )

    parser.add_argument('--find-offset-of', metavar='audio file', type=str,
                        help='Find the offset of file')
    parser.add_argument('--within', metavar='audio file', type=str,
                        help='Within file')
    parser.add_argument('--sr', metavar='sample rate', type=int, default=8000,
                        help='Target sample rate during downsampling')
    parser.add_argument('--trim', metavar='seconds', type=int, default=60*15,
                        help='Only uses first n seconds of audio files')
    parser.add_argument('--resolution', metavar='samples', type=int, default=128,
                        help='Resolution (maximum accuracy) of search in samples')
    parser.add_argument('--show-plot', action='store_true', dest='show_plot',
                        help='Display plot of cross-correlation results')
    parser.add_argument('--save-plot',  metavar='plot file', dest='plot_file', type=str,
                        help=('Save a plot of cross-correlation results to a file '
                              '(format matches extension - png, ps, pdf, svg)'))
    args = parser.parse_args(argv)
    if not (args.find_offset_of and args.within):
        parser.error("Please provide input audio files")
    results = find_offset(args.within,
                          args.find_offset_of,
                          fs=int(args.sr),
                          trim=int(args.trim),
                          hop_length=int(args.resolution))
    print("Offset: %s (seconds)" % str(results["offset"]))
    print("Standard score: %s" % str(results["score"]))
    if args.show_plot or args.plot_file is not None:
        import matplotlib.pyplot as pyplot
        pyplot.figure(figsize=(15, 5))
        pyplot.plot(results["correlation"])
        if args.plot_file is not None:
            pyplot.savefig(args.plot_file)
        if args.show_plot:
            pyplot.show()


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
