# pip3 install inotify
import inotify.adapters

# pip3 install twitch-python
import twitch

import subprocess
import os

def _main():
    chat = twitch.Chat(channel='#sonic7406',
                       nickname='sonic7406',
                       oauth='oauth:oauth', # https://twitchapps.com/tmi/
                       helix=twitch.Helix(client_id='client_id', client_secret='client_secret', use_cache=True)) # https://dev.twitch.tv/console/apps


    i = inotify.adapters.Inotify()

    i.add_watch('/home/sonic')

#    with open('/tmp/test_file', 'w'):
#        pass
# PATH=[/home/sonic] FILENAME=[8J6A0145.HIF] EVENT_TYPES=['IN_CLOSE_WRITE']


    for event in i.event_gen(yield_nones=False):
        (_, type_names, path, filename) = event

        if 'IN_MODIFY' in type_names:
            print('.', end='', flush=True)
        else:
            print("PATH={} FILENAME={} EVENT_TYPES={}".format(path, filename, type_names))
        
        if 'IN_CLOSE_WRITE' in type_names:
            prefix="/home/public/de/killig/sven/photos/twitch/"
            file_name, file_extension = os.path.splitext(filename)
            print("file_name={} file_extension={}".format(file_name, file_extension))
            if file_name.startswith("8J6A") and file_extension==".HIF":
                subprocess.run("mv "+path+"/"+filename+" "+prefix, shell=True)
                target=prefix+file_name+".jpg"

                # ToDo apt install libheif-examples
                # heif_convert="LD_LIBRARY_PATH=/usr/local/lib /usr/local/bin/heif-convert "+prefix+filename+" "+target
                heif_convert="heif-convert "+prefix+filename+" "+target
                print(heif_convert)
                subprocess.run(heif_convert, shell=True)

                exiftool="exiftool -overwrite_original -q -tagsFromFile /home/www/twitch/213678.icc -ICC_Profile "+target
                print(exiftool)
                subprocess.run(exiftool, shell=True)

                chat.send("I just took a photo: HEIX (HDR10 4:2:2) https://sven.killig.de/photos/twitch/"+filename+" | JPEG (4:2:0) https://sven.killig.de/photos/twitch/"+file_name+".jpg")

if __name__ == '__main__':
    _main()
