"""
Author: Michel Peltriaux
Organization: Struktur- und Genehmigungsdirektion Nord, Rhineland-Palatinate, Germany
Contact: michel.peltriaux@sgdnord.rlp.de
Created on: 10.11.21

"""
import csv

from codelist.models import KonovaCodeList
from konova.management.commands.setup import BaseKonovaCommand


class Command(BaseKonovaCommand):
    help = "Exports a single list of internal codes. Codelist identifier must be provided as argument"
    list_id = 'list_id'
    save_to = 'save_to'

    def add_arguments(self, parser):
        try:
            parser.add_argument(self.list_id, type=int)
        except ValueError:
            self._write_error("No list id provided")
            exit(-1)
        try:
            parser.add_argument(self.save_to, type=str)
        except ValueError:
            self._write_error("No save to path given")
            exit(-1)

    def handle(self, *args, **options):
        try:
            list_id = options[self.list_id]
            self.save_to = options[self.save_to]
            self._write_warning("Fetching codes...")
            code_list = KonovaCodeList.objects.get(
                id=list_id,
            )
            codes = code_list.codes.filter(
                is_selectable=True,
            ).order_by(
                "parent"
            )
            header_row = [
                "Parent long name",
                "Parent short name",
                "Code long name",
                "Code short name",
                "Code ID",
            ]
            with open(self.save_to, 'w', newline='') as csvfile:
                writer = csv.writer(
                    csvfile,
                    delimiter=' ',
                    quoting=csv.QUOTE_MINIMAL,
                )
                writer.writerow(header_row)
                for code in codes:
                    if code.parent is not None:
                        row = [code.parent.long_name, code.parent.short_name, code.long_name, code.short_name, code.id]
                    else:
                        row = ["", "", code.long_name, code.short_name, code.id]
                    #row = f"{code.parent.long_name};{code.parent.short_name};{code.long_name};{code.short_name};{code.id}"
                    writer.writerow(row)

        except KeyboardInterrupt:
            self._break_line()
            exit(-1)
