import os
import shutil
import configparser
import requests
import datetime
import zipfile
import uuid
import re
import subprocess as sp

from flask import current_app as app
from aslo.service import activity as activity_service
from aslo.celery_app import logger
from .exceptions import ReleaseError, BuildProcessError, ScreenshotDoesNotExist
from . import gh
from . import i18n
from . import img


def get_bundle_path(bundle_name):
    return os.path.join(app.config['BUILD_BUNDLE_DIR'], bundle_name)


def xo_file_exists(assets):
    for asset in assets:
        if '.xo' in asset['name']:
            logger.info('Attached xo file has been found.')
            return asset

    logger.info('No attached xo file has been found.')
    return None


def download_attached_xo(xo):
    # save on blocks of 1024
    logger.info("Downloading {} file...".format(xo['name']))
    response = requests.get(xo['browser_download_url'], stream=True)
    tmp_bundle_path = os.path.join(app.config['TEMP_BUNDLE_DIR'], xo['name'])
    with open(tmp_bundle_path, "wb") as fh:
        for block in response.iter_content(chunk_size=1024):
            fh.write(block)

    return tmp_bundle_path


def verify_and_extract_xo(tmp_bundle_path):
    def verify_xo(xo_archive):
        logger.info('Searching for activity.info inside xo file.')
        valid = any(
            'activity.info' in filename for filename in xo_archive.namelist()
        )
        if not valid:
            raise ReleaseError('activity.info not found in xo file.')
        else:
            logger.info('activity.info file has been found in xo file.')

        # TODO: are we going to store this locally and/or in remote server?
        bundle_name = os.path.basename(tmp_bundle_path)
        bundle_path = get_bundle_path(bundle_name)
        if os.path.exists(bundle_path) and os.path.isfile(bundle_path):
            raise ReleaseError(
                'Bundle {} already exist.'.format(bundle_name)
            )

    def extract_xo(xo_archive):
        random_uuid = uuid.uuid4().hex
        extract_dir = os.path.join(app.config['TEMP_BUNDLE_DIR'], random_uuid)
        try:
            os.mkdir(extract_dir)
        except (IOError, FileExistsError) as e:
            raise ReleaseError(