# Path: borme/models.py
# class Config(m.Model):
#     last_modified = m.DateTimeField()
#     version = m.CharField(max_length=50)
# 
# Path: borme/parser/importer.py
# def import_borme_download(date_from, date_to, seccion=bormeparser.SECCION.A,
#                           local_only=False, no_missing=False):
#     """Descarga e importa BORMEs desde la web del Registro Mercantil.
# 
#     Descarga BORMEs en formato PDF de la web del Registro Mercantil para
#     un rango de fechas, los convierte a formato BORME-JSON e importa los
#     datos en la BD.
# 
#     :param date_from: Fecha desde la que importar ("2015-01-30", "init")
#     :param date_to: Fecha hasta la que importar ("2015-01-30", "today")
#     :param seccion: Seccion del BORME
#     :param local_only: No descarga archivos, solo procesa archivos ya presentes
#     :param no_missing: Aborta el proceso tan pronto como se encuentre un error
#     :type date_from: str
#     :type date_to: str
#     :type seccion: bormeparser.SECCION
#     :type local_only: bool
#     :type no_missing: bool
#     """
#     if date_from == 'init':
#         date_from = FIRST_BORME[2009]
#     else:
#         date = tuple(map(int, date_from.split('-')))  # TODO: exception
#         date_from = datetime.date(*date)
# 
#     if date_to == 'today':
#         date_to = datetime.date.today()
#     else:
#         date = tuple(map(int, date_to.split('-')))  # TODO: exception
#         date_to = datetime.date(*date)
# 
#     if date_from > date_to:
#         raise ValueError('date_from > date_to')
# 
#     try:
#         ret, _ = _import_borme_download_range(date_from, date_to, seccion,
#                                               local_only, strict=no_missing)
#         return ret
#     except BormeDoesntExistException:
#         logger.info("It looks like there is no BORME for this date ({}). "
#                     "Nothing was downloaded".format(date_from))
#         return False
# 
# Path: libreborme/utils.py
# def get_git_revision_short_hash():
#     os.chdir(os.path.dirname(libreborme.__file__))
#     try:
#         version = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).strip()
#         if isinstance(version, bytes):
#             version = version.decode('unicode_escape')
#     except subprocess.CalledProcessError:
#         logger.warning("Couldn't guess git revision")
#         version = 'Unknown'
#     return version


from django.core.management.base import BaseCommand
from django.utils import timezone
from borme.models import Config
from borme.parser.importer import import_borme_download
from libreborme.utils import get_git_revision_short_hash
import logging
import time
import borme.parser.importer
                help='ISO formatted date (ex. 2015-01-01) or "init"')
        parser.add_argument(
                '-t', '--to',
                nargs=1, required=True,
                help='ISO formatted date (ex. 2016-01-01) or "today"')
        parser.add_argument(
                '--local-only',
                action='store_true',
                default=False,
                help='Do not download any file')
        parser.add_argument(
                '--no-missing',
                action='store_true',
                default=False,
                help='Abort if local file is not found')
        # json only, pdf only...

    def handle(self, *args, **options):
        self.set_verbosity(int(options['verbosity']))
        start_time = time.time()

        import_borme_download(options['from'][0],
                              options['to'][0],
                              local_only=options['local_only'],
                              no_missing=options['no_missing'])

        config = Config.objects.first()
        if config:
            config.last_modified = timezone.now()
        else:

# Path: borme/models.py
# class Config(m.Model):
#     last_modified = m.DateTimeField()
#     version = m.CharField(max_length=50)
# 
# Path: borme/parser/importer.py
# def import_borme_download(date_from, date_to, seccion=bormeparser.SECCION.A,
#                           local_only=False, no_missing=False):
#     """Descarga e importa BORMEs desde la web del Registro Mercantil.
# 
#     Descarga BORMEs en formato PDF de la web del Registro Mercantil para
#     un rango de fechas, los convierte a formato BORME-JSON e importa los
#     datos en la BD.
# 
#     :param date_from: Fecha desde la que importar ("2015-01-30", "init")
#     :param date_to: Fecha hasta la que importar ("2015-01-30", "today")
#     :param seccion: Seccion del BORME
#     :param local_only: No descarga archivos, solo procesa archivos ya presentes
#     :param no_missing: Aborta el proceso tan pronto como se encuentre un error
#     :type date_from: str
#     :type date_to: str
#     :type seccion: bormeparser.SECCION
#     :type local_only: bool
#     :type no_missing: bool
#     """
#     if date_from == 'init':
#         date_from = FIRST_BORME[2009]
#     else:
#         date = tuple(map(int, date_from.split('-')))  # TODO: exception
#         date_from = datetime.date(*date)
# 
#     if date_to == 'today':
#         date_to = datetime.date.today()
#     else:
#         date = tuple(map(int, date_to.split('-')))  # TODO: exception
#         date_to = datetime.date(*date)
# 
#     if date_from > date_to:
#         raise ValueError('date_from > date_to')
# 
#     try:
#         ret, _ = _import_borme_download_range(date_from, date_to, seccion,
#                                               local_only, strict=no_missing)
#         return ret
#     except BormeDoesntExistException:
#         logger.info("It looks like there is no BORME for this date ({}). "
#                     "Nothing was downloaded".format(date_from))
#         return False
# 
# Path: libreborme/utils.py
# def get_git_revision_short_hash():
#     os.chdir(os.path.dirname(libreborme.__file__))
#     try:
#         version = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).strip()
#         if isinstance(version, bytes):
#             version = version.decode('unicode_escape')
#     except subprocess.CalledProcessError:
#         logger.warning("Couldn't guess git revision")
#         version = 'Unknown'
#     return version


# Path: borme/management/commands/importborme.py
from django.core.management.base import BaseCommand
from django.utils import timezone
from borme.models import Config
from borme.parser.importer import import_borme_download
from libreborme.utils import get_git_revision_short_hash
import logging
import time
import borme.parser.importer

                help='ISO formatted date (ex. 2015-01-01) or "init"')
        parser.add_argument(
                '-t', '--to',
                nargs=1, required=True,
                help='ISO formatted date (ex. 2016-01-01) or "today"')
        parser.add_argument(
                '--local-only',
                action='store_true',
                default=False,
                help='Do not download any file')
        parser.add_argument(
                '--no-missing',
                action='store_true',
                default=False,
                help='Abort if local file is not found')
        # json only, pdf only...

    def handle(self, *args, **options):
        self.set_verbosity(int(options['verbosity']))
        start_time = time.time()

        import_borme_download(options['from'][0],
                              options['to'][0],
                              local_only=options['local_only'],
                              no_missing=options['no_missing'])

        config = Config.objects.first()
        if config:
            config.last_modified = timezone.now()
        else:

            config = Config(last_modified=timezone.now())