import tarfile
# import os.path
import os
import datetime
import shutil
from pathlib import Path

# TODO:


from homepage.settings import BASE_DIR


# TARGET can be 'qs' or 'prod'
TARGET = 'prod'
SOFTWARENAME = str(Path(__file__).resolve().parent).split('/')[-1]

PATH_ADD_FILES = f'/home/tobidot/production/{SOFTWARENAME}/{TARGET}'

EXCLUDES = [
    ('file', '/db.sqlite3'),
    ('file', '/deployment.py'),
    ('file', '/readme.md'),
    ('file', '/settings.py'),
    ('file', '/css_input.css'),
    ('file', '/tailwind.config.js'),
    ('file', '.pkl'),
    ('file', '.del'),
    ('file', '.bckp'),
    ('file', '.po'),
    ('dict', '/__pycache__'),
]

DAILYREVISION = None


def manipulate_html(tarinfo):
    ''' create a temparary copy and add the DAILYREVISION to the static
        content in the html templates
        '''

    with open(f'/{tarinfo.name}', 'r') as f_in:

        # iterate over dirs and try to create the needed foldes.
        dir_str = f'{str(BASE_DIR)[:-7]}temp_html/'
        for dir in tarinfo.name[len(str(BASE_DIR)):].split('/')[:-1]:
            try:
                os.mkdir(f'{dir_str}{dir}')
                dir_str += f'{dir}/'
            except Exception as e:
                dir_str += f'{dir}/'
                pass

        # make a copy line by line and add the DAILYREVISION to js and css content
        with open(f'{str(BASE_DIR)[:-7]}temp_html/{tarinfo.name[len(str(BASE_DIR)):]}', 'a') as f_out:
            for row in f_in:
                if '.js\' %}"></script>' in row:
                    f_out.write(row[:row.find('.js\' %}"></script>')] + '-' + DAILYREVISION + '.js\' %}"></script>\n')
                elif '.css\' %}" rel="stylesheet">' in row:
                    f_out.write(row[:row.find('.css\' %}" rel="stylesheet">')] + '-' + DAILYREVISION + '.css\' %}" rel="stylesheet">\n')
                else:
                    f_out.write(row)

def filter_htlm(tarinfo):
    ''' Change file path from temp_folder to correct path insite the archive '''
    tarinfo.name = f'{SOFTWARENAME}/{tarinfo.name[len(f"{str(BASE_DIR)[:-7]}temp_html"):]}'
    return tarinfo

def filter_function(tarinfo):
    ''' Exclude some dirs and files that are not necessary for production.
        Create temp copies of html files.
        Rename .js and .css files and add the DAILYREVISION.'''
    for k, v in EXCLUDES:
        if k == 'file':
            if tarinfo.name[-len(v):] == v:
                return None
        elif k == 'dict':
            if v in str(tarinfo.name):
                return None

    # to force the clients to load the newest content
    if '/templates/' in tarinfo.name and tarinfo.name[-5:] == '.html':
        # create a temparary copy and add the DAILYREVISION to the static
        # content in the html templates
        manipulate_html(tarinfo)
        return None
    # elif tarinfo.name[-3:] == '.js':
    #     tarinfo.name = f'{SOFTWARENAME}/{tarinfo.name[len(str(BASE_DIR)):-3]}-{DAILYREVISION}.js'
    # elif tarinfo.name[-4:] == '.css':
    #     tarinfo.name = f'{SOFTWARENAME}/{tarinfo.name[len(str(BASE_DIR)):-4]}-{DAILYREVISION}.css'

    else:
        tarinfo.name = f'{SOFTWARENAME}/{tarinfo.name[len(str(BASE_DIR)):]}'

    return tarinfo

def filter_add(tarinfo):
    ''' Change file path from temp_folder to correct path insite the archive '''
    tarinfo.name = f'{SOFTWARENAME}/{tarinfo.name[len(str(PATH_ADD_FILES)):]}'
    return tarinfo

if __name__ == "__main__":

    # quit()


    DAILYREVISION = datetime.datetime.now().strftime(f"%Y%m%d%H%M")

    # Delete Temp_Folder for html files
    os.mkdir(f'{str(BASE_DIR)[:-7]}temp_html')

    tar = tarfile.open(f"/home/tobidot/production/{SOFTWARENAME}/{DAILYREVISION}-{SOFTWARENAME}-{TARGET}.tar.gz", "w:gz")
    tar.add(BASE_DIR, recursive = True, filter = filter_function)
    tar.add(PATH_ADD_FILES, recursive = True, filter = filter_add)
    tar.add(f'{str(BASE_DIR)[:-7]}temp_html', recursive = True, filter = filter_htlm)
    tar.close()

    # Delete Temp_Folder
    shutil.rmtree(f'{str(BASE_DIR)[:-7]}temp_html')
