"""
Some FTP related tools that might be handy
"""
import re
import urllib.parse
import pprint as pp


# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def get_file_listing(ftpobj):
    """recursively attempt to get a file listing from the current working
    directory of the ftpobj

    Parameters
    ----------
    ftpobj : `FTP`
        The FTP object generated by ``ftplib.FTP``.

    Returns
    -------
    files : `list` of `str`
        All the files that exist at or below the CWD of the ftpobj.
    """
    # Will hold the contents of the direcory listing
    dir_list = []

    # Will hold the contents of any sub directories that are found when
    # processing the current directory
    sub_dirs = []

    # Get the current working directory
    pwd = ftpobj.pwd()
    # joinpwd = pwd
    # print("FILE LISTING PWD: '{0}'".format(pwd))
    # print(pwd)
    if not pwd.endswith(r'/'):
        pwd = "{0}/".format(pwd)

    # Get the directory content and make sure it is in the directory listing
    # this will be processed later to extract information
    ftpobj.dir(dir_list.append)

    # Now loop through the directory list and process the output, we also
    # tranverse to any other directories we find on the way
    for c, d in enumerate(dir_list):
        # print(c)
        # print(d)

        # Get all the groups
        try:
            lp = re.match(r'^(?P<dir>[-ld])(?P<permission>([-r][-w][-xs]){3})\s+'
                          r'(?P<filecode>\d+)\s+(?P<owner>\w+)\s+(?P<group>\w+)\s+'
                          r'(?P<size>\d+)\s+(?P<timestamp>((?P<month>\w{3})\s+'
                          r'(?P<day>\d{2})\s+(?P<hour>\d{1,2}):(?P<minute>\d{2}))'
                          r'|((?P<month2>\w{3})\s+(?P<day2>\d{2})\s+(?P<year2>'
                          r'\d{4})))\s+(?P<name>.+)$', d)

            atts = lp.groupdict()
        except (AttributeError, TypeError):
            # If it is None, there presumably there is no listsing, so just
            # move on perhaps i should just change this to break?
            # print("CONTINUE AFTER")
            # print(d)
            continue

        # change the relative name to an absolute one
        # print("FILE LISTING PWD: '{0}'".format(pwd))
        # print("FILE LISTING ATTS")
        # print(atts['name'])
        atts['name'] = urllib.parse.urljoin(pwd, atts['name'])
        # pp.pprint(atts)

        if atts['dir'] == "d":
            # print(atts)
            # Move to the nested directory and then process
            ftpobj.cwd(atts['name'])
            sub_dirs.extend(get_file_listing(ftpobj))
        else:
            sub_dirs.append(atts)

    # Make sure the FTP object is back to where we started
    ftpobj.cwd(pwd)

    # Add any files in subdirs to the directory list
    # dir_list.extend(sub_dirs)
    return sub_dirs
