from django.core.management.base import BaseCommand, CommandError
from products.models import *

class Command(BaseCommand):
    help = 'Export batch to a file'

    def add_arguments(self, parser):
        parser.add_argument('--batch', '-b', type=int, required=True, help="batch id")
        parser.add_argument('--output', '-o', required=True, help="output file")
        parser.add_argument('--job', '-j', type=int, help="The job object to report progress")
        parser.add_argument('--pattern', '-P', default='{code}', help="The pattern of each line, where {code} is replaced with the serial code")

    def handle(self, *args, **options):
        batch_id = options['batch']
        if options.get('job'):
            job = Job.objects.get(pk=options['job'])
        else:
            job = Job.objects.create(name='export-batch.%d' % batch_id)
        try:
            job.update('running', 0.0)
            b = CodeBatch.objects.get(pk=batch_id)
            fn = open(options['output'], 'w', encoding='utf-8')
            ac = b.codes.all().order_by('seq_num')
            total = ac.count()
            done = 0
            for c in ac.iterator():
                line = options['pattern']
                line = line.replace('{code}', c.code)
                line = line.replace('{seq}', str(c.seq_num) if c.seq_num else "0")

                fn.write(line + "\n")
                done += 1
                if done % 10000 == 0:
                    perc = done * 100.0 / total
                    print("[%d/%d %.1f%%]" % (done, total, perc))
                    job.update('running', perc)
            print("all done, exported %d codes" % total)
            fn.flush()
            job.update('done', 100.0)
            fn.flush()
        except Exception as e:
            job.update('error', message=str(e))
