import logging
import ftplib


def ftp_check_directory(ftp_connection, path):
    """
    Following convention with the rest of the code,
    return 0 if it is a directory, 1 if it is not or failed to do the check
    """
    response = ftp_connection.pwd()
    if response == '':
        return 1
    original_directory = response

    # We are NOT scp, so we won't create a file when filename is not
    # specified (mirrors input behaviour)
    try:
        ftp_connection.cwd(path)
        logging.error(
            'Path "%s" at "%s" already exists and is a folder. \
            Please specify a target filename and retry',
            path, ftp_connection.host)
        is_directory = True
    except ftplib.error_perm:
        is_directory = False
    except (ftplib.error_reply, ftplib.error_temp):
        logging.exception('Could not check if path "%s" in "%s" is directory',
                          path, ftp_connection.host)
        return 1
    try:
        ftp_connection.cwd(original_directory)
    except (ftplib.error_reply, ftplib.error_perm, ftplib.error_temp):
        logging.exception(
            'Error when checking if "%s" in "%s" was a directory',
            path, ftp_connection.host)
        return 1

    return 0 if is_directory else 1