"""
Script for investigating which IPTC PMD properties are embedded into an image file, and which not

"""
import os
import shutil
import yaml
import datetime
from scripts import ipmdchecker2 as ipmdchecker

currentdir: str = os.path.dirname(os.path.realpath(__file__))

CONFIGFP: str = currentdir + '/config/scriptsconfig.yml'
with open(CONFIGFP) as yaml_file1:
    scriptconfigs = yaml.safe_load(yaml_file1)

FILESDIR: str = currentdir + '/' + scriptconfigs['general']['filespathrel']
TESTRESULTSDIR = FILESDIR + 'testresults/'
LOGFP = TESTRESULTSDIR + 'testresults_all.txt'

# Investigate1 specific directories
INV1DIR: str = FILESDIR + 'investigate1/'
CACHEINV1DIR: str = FILESDIR + 'cache/investigate1/'
BACKUPINV1DIR: str = FILESDIR + 'backup/investigate1/'


def run_investigation1(testimgfn: str) -> None:
    """Runs IPTC Photo Metadata Interoperability Test #3 with a single image file

    :param testimgfn: file name of the to be tested image file
    :return: nothing
    """
    coretestimgfn = os.path.splitext(testimgfn)[0]
    testimgfp = INV1DIR + testimgfn
    testjsonfp = CACHEINV1DIR + coretestimgfn + '.json'
    testresults_text_1fp = TESTRESULTSDIR + coretestimgfn + '_inv1.txt'
    testresults_csv_1fp = TESTRESULTSDIR + coretestimgfn + '_inv1.csv'
    backupimgfp = BACKUPINV1DIR + testimgfn

    ipmdchecker.readpmd_exiftool(testimgfp, testjsonfp)
    if os.path.isfile(testjsonfp):
        msg = 'Investigated(1) JSON file of image: ' + testimgfn
        print(msg)
        ipmdchecker.append_line2file(msg, LOGFP)
        ipmdchecker.append_line2file(msg, testresults_text_1fp)
        msg = 'Tested on: ' + datetime.datetime.now().astimezone().replace(microsecond=0).isoformat()
        print(msg)
        ipmdchecker.append_line2file(msg, LOGFP)
        ipmdchecker.append_line2file(msg, testresults_text_1fp)

        ipmdchecker.investigate_mainpmd(testjsonfp, testresults_text_1fp, testresults_csv_1fp)
        ipmdchecker.append_line2file('***** TEST FINISHED *****', testresults_text_1fp)
        shutil.move(testimgfp, backupimgfp)
    else:
        print(f'No JSON file generated by ExifTool for {testjsonfp}')


def testdummy1():
    # testfilename = '_testimg_AdobeLrC_10_allPmdFilled_1d'
    testfilename = '_IPTC-PhotometadataRef-Std2019.1_2'
    testfp = '../files/cache/investigate1/' + testfilename + '.json'
    testresults_txt_1fp = TESTRESULTSDIR + testfilename + '_inv1.txt'
    testresults_csv_1fp = TESTRESULTSDIR + testfilename + '_inv1.csv'
    ipmdchecker.append_line2file('Tested JSON file: ' + testfp, testresults_txt_1fp)
    ipmdchecker.investigate_mainpmd(testfp, testresults_txt_1fp, testresults_csv_1fp)


if __name__ == '__main__':

    DEV: bool = False

    if DEV:
        testdummy1()
    else:
        foundinv1images = ipmdchecker.find_testfiles(INV1DIR)
        print(foundinv1images)
        for singletestimgfn in foundinv1images:
            run_investigation1(singletestimgfn)
