from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils import timezone
from limitmonitor.models import ExternalBundle
import argparse
import strictyaml
from purist.limitmonitor import ServicesContainer


class Command(BaseCommand):
    help = 'Generates ExternalBundle entries as specified in yaml input file'

    def add_arguments(self, parser):
        parser.add_argument('file', type=argparse.FileType('r'))

    def handle(self, *args, **options):

        infile = options['file']
        with open(infile.name, 'r') as stream:
            bundles = strictyaml.load(stream.read()).data

        # ordered dict with uppercase service name as keys used to get
        # service value from name
        ser_values = {n.upper(): v for v, n in ServicesContainer.MAP.items()}
        now = timezone.now()

        for bundle in bundles:
            msg = 'Proccessing {} bundle.'.format(bundle['name'])
            self.stdout.write(msg)
            count = 0

            for id in bundle['ids']:
                for service in bundle['services']:
                    ser_val = ser_values[service.upper()]
                    cur_bund = ExternalBundle.objects.filter(
                        external_key=id).filter(service=ser_val)
                    if len(cur_bund) == 0:
                        eb = ExternalBundle(
                            parser=settings.LM_PARSERS.WOO_SUBSCRIPTION_V1,
                            external_key=id,
                            service=ser_val,
                            created_date=now
                        )
                        eb.save()
                        count += 1
            msg = '  {} entries added.'.format(count)
            self.stdout.write(msg)
