#! /usr/bin/python
# -*- mode: python -*-
from contextlib import contextmanager
import glob
import itertools
import logbook
import os
import re
import stat
import shutil
import subprocess
import tempfile
from raven import Client
from rq_queues import default_queue, retry_queue
from sentry_dsn import SENTRY_DSN

sentry = Client(SENTRY_DSN)

_logger = logbook.Logger(__name__)

def unzip_docs(filename, dest, package_name, version):
    directory = os.path.dirname(filename)
    sphinx_dir = os.path.join(directory, "sphinx", "html")
    if not os.path.isdir(sphinx_dir):
        os.makedirs(sphinx_dir)
    subprocess.check_call(["tar", "xzf", filename, "-C", sphinx_dir])
    os.unlink(filename)

    _write_metadata(directory, package_name=package_name, version=version)
    _move_to_dest(directory, os.path.join(dest, package_name))


def build_docs(repo, dest, pypi=None, retries_left=5):
    try:
        temp_dest = tempfile.mkdtemp()
        with _ensuring_virtualenv() as env:
            with _temporary_checkout(repo, env, pypi) as temp_checkout:
                temp_checkout.write_metadata(temp_dest)
                temp_checkout.generate_sphinx(os.path.join(temp_dest, "sphinx"))
                temp_checkout.generate_dash(os.path.join(temp_dest, "dash"))
                temp_checkout.write_metadata(temp_dest)
                _move_to_dest(temp_dest, os.path.join(dest, temp_checkout.get_package_name()))
            return 0
    except:
        _logger.error("Exception while building docs", exc_info=True)
        retries_left -= 1
        if retries_left <= 0:
            sentry.captureException()
        else:
            retry_queue.enqueue_call(
                retry_build_docs,
                args=(repo, dest, pypi, retries_left),