# python function that takes address
# parses it for the youtube icon
# via wget site.com/favicon.ico
# saves it with propername for reference
# later on
import subprocess as sp
# search via regex
import re, os

def check_icon(sitename):
    print('checking icon')##
    # checks for site icon in storage
    str1 = sitename.replace('/', '')
    sitename = f'{str1.replace(":", ".")}.ico'
    path = 'static/sitecons/'

    # list comp for searching through dir for file
    result = [os.path.join(root, sitename) for root, dirs, files in os.walk(path) if sitename in files] 

    if result:
        print('returning True')##
        return f'{sitename}'
    else:
        print('returning False')##
        return False

def fetch_icon(sitename):
    print('fetching icon')##
    path = 'static/sitecons/'

    # search end of string for leading slash
    search_slash = re.findall('\/$', sitename)

    # if theres a slash, no need to append, otherwise
    if search_slash:
        parsed_name = f'{sitename}favicon.ico'
    else:
        parsed_name = f'{sitename}/favicon.ico'

    # remove chars for icon filename
    str1 = sitename.replace('/', '')
    sitename = str1.replace(':', '.')

    print(parsed_name)##
    print(f'wget {parsed_name} -O {path}{sitename}.ico')
    p1 = sp.run(f'wget {parsed_name} -O app/{path}{sitename}.ico', shell=True, capture_output=True, text=True)
    print(p1.stdout)##
    print('checking icon')##

    return f'{sitename}.ico'
