import logging
import os
import shutil

from config import CONFIG

log = logging.getLogger('hunter')

def save_html(path, html):
    """Writes html to a file.

    Args:
        path: Name of the folder.
        html: HTML string

    Returns:
        None
    """
    file = os.path.join(path, 'page.html')

    with open(file, 'w', encoding = 'utf-8') as f:
        f.write(html)

def create_folder(name):
    """Creates a new folder.

    Args:
        name: Name of the folder.

    Returns:
        Absolute PATH of the created folder.
    """
    path = os.path.join(CONFIG['DIR']['DOWNLOAD'], name)

    if not os.path.exists(path):
        os.makedirs(path)
        log.info('Hunter: created folder: \'' + path + '\'')

    return path

def folder_exists_and_has_content(name):
    """Checks if a folder already exists and has content.

    Args:
        name: Name of the folder.

    Returns:
        If Folder exists and has content.
    """
    has_content = False
    path = os.path.join(CONFIG['DIR']['DOWNLOAD'], name)

    if os.path.exists(path):
        for file in os.scandir(path):
            if '.mp3' in file.name:
                has_content = True

    return has_content

def has_download_finished(path):
    """Checks if download has finished.

    Args:
        path: Absolute PATH for folder.

    Returns:
        Boolean of download status.
    """
    finished = True

    for file in os.listdir(path):
        if 'crdownload' in file:
            finished = False

    return finished

def save_status(status, url, name):
    """Log status and depending on that remove folder.

    Args:
        status: Returned status of crawler.
        url: Search URL.
        name: Name of the folder.

    Returns:
        None
    """
    path = os.path.join(CONFIG['DIR']['DOWNLOAD'], name)

    print(status, url)

    if status == 'Failed' or status == 'Canceled':
        try:
            shutil.rmtree(path)
        except Exception as err:
            log.exception('Hunter: Exception occurred in save_status function.')

    log.info('Hunter: ' + status + ' on \'' + url + '\'')