import os
from posixpath import ismount
import sys
import time
import subprocess
import datetime
import shutil
import json

_DEST = "/share/Photo/imported"
_DEV = ""
_DEV_MOUNT = "/share/external/DEV3304_1/"
_DEV_DIR = "/share/external/DEV3304_1/DCIM/100GOPRO"
_IMP_FILE = "/share/external/DEV3304_1/auto_import"
_DEV_DATA = "/share/external/DEV3304_1/MISC/version.txt"


print("###############")

#sys.exit()
while True:
    if os.path.ismount(_DEV_MOUNT):
        if os.path.exists(_DEV_DATA):
            file = open(_DEV_DATA, 'r')
            content = file.read()
            file.close()
            strToReplace   = ','
            replacementStr = ''
            strToReplaceReversed   = strToReplace[::-1]
            replacementStrReversed = replacementStr[::-1]
            
            strValue = content[::-1].replace(strToReplaceReversed, replacementStrReversed, 1)[::-1]
            c = content.replace("\n","")
            
            print("--------------")
            print(c[-2])
            print("--------------")
            print(strValue)
            _DEV_CONT = json.loads(strValue)
            print(_DEV_CONT)
            print(_DEV_CONT["wifi mac"])
            wifimac = _DEV_CONT["wifi mac"]
            if wifimac == "2474f742c017":
                _DEV = "gopro9_1"
                print("gopro9_1 registered")
                
        if os.path.exists(_IMP_FILE) and _DEV == "":      
            print("path exist")
            time.sleep(5)
            if _DEV == "":
                file = open(_IMP_FILE, 'r')
                content = file.read()
                _DEV = json.loads(content)["device"]
            file.close()
            x = datetime.datetime.now()
            print(x.year)
            _DAT = x.strftime("%Y%m%d")
            if len(os.listdir(_DEV_DIR)) == 0:
                print("Folder is empty!")
                myCmd = "umount /share/external/DEV3304_1"
                status, output = subprocess.getstatusoutput(myCmd)
                time.sleep(5)
                continue
            myCmd = "/sbin/hal_app --se_buzzer enc_id=0,mode=101;sleep 1;/sbin/hal_app --se_buzzer enc_id=0,mode=101;sleep 1;/sbin/hal_app --se_buzzer enc_id=0,mode=101"
            status, output = subprocess.getstatusoutput(myCmd)
        if not _DEV == "":
            if os.path.exists(_DEV_DIR):
                for filename in os.listdir(_DEV_DIR):
                    print(filename)
                    c_time = os.path.getctime("{}/{}".format(_DEV_DIR,filename))
                    dt_c = datetime.datetime.fromtimestamp(c_time)
                    print(dt_c)
                    _CDAT = dt_c.strftime("%Y-%m-%d")
                    print(_CDAT)
                    _FDEST = "{}/{}/{}".format(_DEST,_DEV, _CDAT)
                    if not os.path.exists(_FDEST):
                        cmnd = "mkdir -p {}".format(_FDEST)
                        status, output = subprocess.getstatusoutput(cmnd)
                    print("Moving file {} into {}".format(filename, _FDEST))
                    try:                                
                        shutil.move("{}/{}".format(_DEV_DIR,filename),_FDEST)
                    except:
                        try:
                            shutil.move("{}/{}".format(_DEV_DIR,filename),"{}/{}".format(_FDEST,filename))
                        except:
                            print("failed to move file {}".format(filename))
                print("Umounting")
                myCmd = "umount /share/external/DEV3304_1"
                status, output = subprocess.getstatusoutput(myCmd)
                print(output)
                print(status)
                myCmd = "/sbin/hal_app --se_buzzer enc_id=0,mode=100"
                subprocess.getstatusoutput(myCmd)
                time.sleep(5)
            else:
                print("Nothing to import")
                time.sleep(5)
        else:
            print("Unknown device")
            time.sleep(5)
    else:
        print("Usb does not connected")
        time.sleep(5)