# Path: bormeparser/exceptions.py
# class BormeDoesntExistException(BormeparserException):
#     pass
# 
# Path: bormeparser/parser.py
# def parse(data, seccion):
#     module = importlib.import_module(DEFAULT_PARSER[seccion][0])
#     parser = getattr(module, DEFAULT_PARSER[seccion][1])
#     if os.path.isfile(data):
#         borme = parser(data).parse()
#     elif data.startswith('http'):
#         # TODO
#         # req = requests.get(data)
#         # content = req.text
#         borme = parser(data).parse()
#     else:
#         raise IOError(data)
# 
#     return borme
# 
# Path: bormeparser/seccion.py
# class SECCION:
#     A = 'A'
#     B = 'B'
#     C = 'C'
# 
#     # TODO: No detecta tipo C, viene el texto comprimido
#     @staticmethod
#     def from_borme(seccion, subseccion):
#         if seccion in ('SECCIÓN PRIMERA', 'SECCIÓN PRIMERA'):
#             if subseccion == 'Actos inscritos':
#                 return SECCION.A
#             elif subseccion == 'Otros actos publicados en el Registro Mercantil':
#                 return SECCION.B
#             else:
#                 raise ValueError('InvalidSeccion: %s %s' % (seccion, subseccion))
#         else:
#             raise ValueError('InvalidSeccion: %s %s' % (seccion, subseccion))


import datetime
import os
import requests
import time
import logging
from lxml import etree
from threading import Thread
from .exceptions import BormeDoesntExistException
from .parser import parse as parse_borme
from .seccion import SECCION
from queue import Queue

logger = logging.getLogger(__name__)
ch = logging.StreamHandler()
logger.addHandler(ch)
logger.setLevel(logging.WARN)

# URLs

# DON'T REWRITE BY DEFAULT
# TODO: comprobar bytes

# TODO: boe.gob.es es un mirror? Resuelve a una IP distinta.
BORME_AB_PDF_URL = "{protocol}://boe.es/borme/dias/{year}/{month:02d}/{day:02d}/pdfs/BORME-{seccion}-{year}-{nbo}-{provincia}.pdf"
BORME_XML_URL = "{protocol}://www.boe.es/diario_borme/xml.php?id=BORME-S-{year}{month:02d}{day:02d}"
BORME_C_HTM_URL = "{protocol}://boe.es/diario_borme/txt.php?id=BORME-C-{year}-{anuncio}"
BORME_C_PDF_URL = "{protocol}://boe.es/borme/dias/{year}/{month:02d}/{day:02d}/pdfs/BORME-C-{year}-{anuncio}.pdf"
BORME_C_XML_URL = "{protocol}://boe.es/diario_borme/xml.php?id=BORME-C-{year}-{anuncio}"

URL_BASE = '%s://www.boe.es'
USE_HTTPS = True

# Download threads
THREADS = 8


# date = (year, month, date) or datetime.date
# filename = path to filename or just filename
def download_xml(date, filename, secure=USE_HTTPS):
    url = get_url_xml(date, secure=secure)
    downloaded = download_url(url, filename)

# Path: bormeparser/exceptions.py
# class BormeDoesntExistException(BormeparserException):
#     pass
# 
# Path: bormeparser/parser.py
# def parse(data, seccion):
#     module = importlib.import_module(DEFAULT_PARSER[seccion][0])
#     parser = getattr(module, DEFAULT_PARSER[seccion][1])
#     if os.path.isfile(data):
#         borme = parser(data).parse()
#     elif data.startswith('http'):
#         # TODO
#         # req = requests.get(data)
#         # content = req.text
#         borme = parser(data).parse()
#     else:
#         raise IOError(data)
# 
#     return borme
# 
# Path: bormeparser/seccion.py
# class SECCION:
#     A = 'A'
#     B = 'B'
#     C = 'C'
# 
#     # TODO: No detecta tipo C, viene el texto comprimido
#     @staticmethod
#     def from_borme(seccion, subseccion):
#         if seccion in ('SECCIÓN PRIMERA', 'SECCIÓN PRIMERA'):
#             if subseccion == 'Actos inscritos':
#                 return SECCION.A
#             elif subseccion == 'Otros actos publicados en el Registro Mercantil':
#                 return SECCION.B
#             else:
#                 raise ValueError('InvalidSeccion: %s %s' % (seccion, subseccion))
#         else:
#             raise ValueError('InvalidSeccion: %s %s' % (seccion, subseccion))


# Path: bormeparser/download.py
import datetime
import os
import requests
import time
import logging
from lxml import etree
from threading import Thread
from .exceptions import BormeDoesntExistException
from .parser import parse as parse_borme
from .seccion import SECCION
from queue import Queue


logger = logging.getLogger(__name__)
ch = logging.StreamHandler()
logger.addHandler(ch)
logger.setLevel(logging.WARN)

# URLs

# DON'T REWRITE BY DEFAULT
# TODO: comprobar bytes

# TODO: boe.gob.es es un mirror? Resuelve a una IP distinta.
BORME_AB_PDF_URL = "{protocol}://boe.es/borme/dias/{year}/{month:02d}/{day:02d}/pdfs/BORME-{seccion}-{year}-{nbo}-{provincia}.pdf"
BORME_XML_URL = "{protocol}://www.boe.es/diario_borme/xml.php?id=BORME-S-{year}{month:02d}{day:02d}"
BORME_C_HTM_URL = "{protocol}://boe.es/diario_borme/txt.php?id=BORME-C-{year}-{anuncio}"
BORME_C_PDF_URL = "{protocol}://boe.es/borme/dias/{year}/{month:02d}/{day:02d}/pdfs/BORME-C-{year}-{anuncio}.pdf"
BORME_C_XML_URL = "{protocol}://boe.es/diario_borme/xml.php?id=BORME-C-{year}-{anuncio}"

URL_BASE = '%s://www.boe.es'
USE_HTTPS = True

# Download threads
THREADS = 8


# date = (year, month, date) or datetime.date
# filename = path to filename or just filename
def download_xml(date, filename, secure=USE_HTTPS):
    url = get_url_xml(date, secure=secure)
    downloaded = download_url(url, filename)

    return downloaded