"""Analyse and check files using Sox, prints good and bad files."""
import logging
from argparse import RawTextHelpFormatter

from django.core.management.base import BaseCommand, CommandError

from aircox.management.sound_stats import SoundStats, SoxStats

logger = logging.getLogger("aircox.commands")


class Command(BaseCommand):
    help = __doc__
    sounds = None

    def add_arguments(self, parser):
        parser.formatter_class = RawTextHelpFormatter

        parser.add_argument(
            "files",
            metavar="FILE",
            type=str,
            nargs="+",
            help="file(s) to analyse",
        )
        parser.add_argument(
            "-s",
            "--sample_length",
            type=int,
            default=120,
            help="size of sample to analyse in seconds. If not set (or 0), "
            "does not analyse by sample",
        )
        parser.add_argument(
            "-a",
            "--attribute",
            type=str,
            help="attribute name to use to check, that can be:\n"
            + ", ".join(['"{}"'.format(attr) for attr in SoxStats.attributes]),
        )
        parser.add_argument(
            "-r",
            "--range",
            type=float,
            nargs=2,
            help="range of minimal and maximal accepted value such as: "
            "--range min max",
        )
        parser.add_argument(
            "-i",
            "--resume",
            action="store_true",
            help="print a resume of good and bad files",
        )

    def handle(self, *args, **options):
        # parameters
        minmax = options.get("range")
        if not minmax:
            raise CommandError("no range specified")

        attr = options.get("attribute")
        if not attr:
            raise CommandError("no attribute specified")

        # sound analyse and checks
        self.sounds = [
            SoundStats(path, options.get("sample_length"))
            for path in options.get("files")
        ]
        self.bad = []
        self.good = []
        for sound in self.sounds:
            logger.info("analyse " + sound.path)
            sound.analyse()
            sound.check(attr, minmax[0], minmax[1])
            if sound.bad:
                self.bad.append(sound)
            else:
                self.good.append(sound)

        # resume
        if options.get("resume"):
            for sound in self.good:
                logger.info("\033[92m+ %s\033[0m", sound.path)
            for sound in self.bad:
                logger.info("\033[91m+ %s\033[0m", sound.path)
