#!/usr/bin/python3

from goprocam import GoProCamera
from goprocam import constants


import os
import sys
import re
import time

log_ptr=None

def msg(str):
   global log_ptr
   if log_ptr!=None:
      log_ptr=str
   else:
      print(str)


def run(filename,ptr=None):
    
   if (ptr):
      log_ptr=ptr
 
   
   file_path = "/backup/"+filename
   
   
   
   if os.path.isdir(file_path):
      msg ("directroy exist "+file_path+" exiting..")
      exit()
   elif os.path.exists(file_path):
      msg ("file exist "+file_path+" exiting..")
      exit()
   
   os.system("mkdir "+file_path)
   print ("mkdir "+file_path)
   
   
   if os.system("ifconfig wlan1 | grep inet") == "":
      msg ("wlan1 not connected to Gopro SSID. exiting...")
      exit()
   
   
   gpCam = GoProCamera.GoPro()
   gpCam.pair(usepin=False)
   #gpCam.pair(usepin=True)
   
   if not os.path.exists(file_path):
      os.makedirs(file_path);
   
   
   msg ("Start...")
   
   localtime = time.asctime( time.localtime(time.time()) )
   start_time = time.time()
   msg ("Start time :", localtime)
   gpCam.overview()
   #msg(gpCam.getMedia())
   #msg(gpCam.getMediaInfo("file"))
   gpCam.listMedia(True)
   #exit()
   
   data=gpCam.listMedia(True,True)
   for i in data:
      folder=i[0]
      if not os.path.exists(file_path+"/"+folder):
         os.makedirs(file_path+"/"+folder);
      mp4_file=i[1]
      lrv_file=re.sub(".MP4",".LRV",mp4_file) 
    
      msg("copy "+folder+"/"+mp4_file+" to "+file_path); 
      gpCam.downloadMedia(folder,mp4_file,file_path+"/"+folder+"/"+mp4_file)
      msg("copy "+folder+"/"+lrv_file+" to "+file_path); 
      gpCam.downloadMedia(folder,lrv_file,file_path+"/"+folder+"/"+lrv_file)
      if re.search("GPBK",mp4_file) or  re.search("GB",mp4_file):
         wav_file=re.sub(".MP4",".WAV",mp4_file)
         #msg("copy "+folder+"/"+wav_file+" to "+file_path); 
         gpCam.downloadMedia(folder,wav_file,file_path+"/"+folder+"/"+wav_file)
      if re.search("GPBK",mp4_file):
         thm_file=re.sub(".MP4",".THM",mp4_file) 
         #msg("copy "+folder+"/"+thm_file+" to "+file_path); 
         gpCam.downloadMedia(folder,thm_file,file_path+"/"+folder+"/"+thm_file)
      if re.search("GPFR",mp4_file):
         thm_file=re.sub(".MP4",".THM",mp4_file) 
         #msg("copy "+folder+"/"+thm_file+" to "+file_path); 
         gpCam.downloadMedia(folder,thm_file,file_path+"/"+folder+"/"+thm_file)
         
   
   
   msg ("Done")
   localtime = time.asctime( time.localtime(time.time()) )
   elapsed_time = time.time() - start_time
   msg ("End time :", localtime)
   
   
   hours, rem = divmod(elasped_time, 3600)
   minutes, seconds = divmod(rem, 60)
   msg("Elaspse time: "+"{:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))
   

if __name__ == '__main__':
   if len(sys.argv) < 2:
      msg ("Usage cp_fusion_files.py <destination directory> ")
      exit()
   
   run(sys.argv[1])