# 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: borme/parser/path.py
# def update_previous_xml(date):
#     """
#     Dada una fecha, comprueba si el XML anterior es definitivo y si no lo es
#     lo descarga de nuevo
#     """
#     xml_path = get_borme_xml_filepath(date)
#     bxml = BormeXML.from_file(xml_path)
# 
#     try:
#         prev_xml_path = get_borme_xml_filepath(bxml.prev_borme)
#         prev_bxml = BormeXML.from_file(prev_xml_path)
#         if prev_bxml.is_final:
#             return False
# 
#         os.unlink(prev_xml_path)
#     except OSError:
#         pass
#     finally:
#         prev_bxml = BormeXML.from_date(bxml.prev_borme)
#         prev_bxml.save_to_file(prev_xml_path)
# 
#     return True


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 borme.parser.path import update_previous_xml
import datetime
import logging
import time
import borme.parser.importer

# from borme.parser.postgres import psql_update_documents


class Command(BaseCommand):
    help = 'Import BORMEs from today'

    def add_arguments(self, parser):
        parser.add_argument('--local-only',
                            action='store_true',
                            default=False,
                            help='Do not download any file')

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

        date = datetime.date.today()
        datestr = date.strftime('%Y-%m-%d')
        success = import_borme_download(datestr,
                                        datestr,
                                        local_only=options['local_only'])

        if success:
            update_previous_xml(date)

            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: borme/parser/path.py
# def update_previous_xml(date):
#     """
#     Dada una fecha, comprueba si el XML anterior es definitivo y si no lo es
#     lo descarga de nuevo
#     """
#     xml_path = get_borme_xml_filepath(date)
#     bxml = BormeXML.from_file(xml_path)
# 
#     try:
#         prev_xml_path = get_borme_xml_filepath(bxml.prev_borme)
#         prev_bxml = BormeXML.from_file(prev_xml_path)
#         if prev_bxml.is_final:
#             return False
# 
#         os.unlink(prev_xml_path)
#     except OSError:
#         pass
#     finally:
#         prev_bxml = BormeXML.from_date(bxml.prev_borme)
#         prev_bxml.save_to_file(prev_xml_path)
# 
#     return True


# Path: borme/management/commands/importbormetoday.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 borme.parser.path import update_previous_xml
import datetime
import logging
import time
import borme.parser.importer


# from borme.parser.postgres import psql_update_documents


class Command(BaseCommand):
    help = 'Import BORMEs from today'

    def add_arguments(self, parser):
        parser.add_argument('--local-only',
                            action='store_true',
                            default=False,
                            help='Do not download any file')

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

        date = datetime.date.today()
        datestr = date.strftime('%Y-%m-%d')
        success = import_borme_download(datestr,
                                        datestr,
                                        local_only=options['local_only'])

        if success:
            update_previous_xml(date)

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

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