import threading
import os
import time
import picamera
import datetime

numberOfImages = 0
inputing = True

days = 0
h = 0
m = 0
s = 0
secounds = 0
delay = 300



while inputing:
  os.system('cls' if os.name == 'nt' else 'clear')
  try:
    numberOfImages = int(raw_input('How many images should be taken? \'0 to ignore\'\n'))
    if numberOfImages == 0:
      days = int(raw_input('How many days should this take?\n'))
      h = int(raw_input('How many hours should this take?\n'))
      m = int(raw_input('How many minutes should this take?\n'))
      s = int(raw_input('How many secounds should this take?\n'))
      pass
    delay = int(raw_input('How long delay (in sec) \n'))
    print "\n\n   In what resolution ?  \n\n"
    inputing = False
    if delay == 0:
      delay = 1
      pass
  except Exception as err:
    print 'Error: ' + err


if numberOfImages == 0:
  days = days * 24 * 60 * 60 
  h = h * 60 * 60
  m = m * 60
  secounds = days + h + m + s

  numberOfImages = secounds / delay
  pass

print "\n\nLoading settings... \n\n"

class timelaps(threading.Thread):
  """docstring for timelaps"""
  def __init__(self, delay, numberOfImages):
    super(timelaps, self).__init__()
    self.delay = delay
    if delay < 20:
      self.delay = 20
      pass
    self.numberOfImages = numberOfImages
    
    
  def run(self):
    currentImage = 0
    camera = picamera.PiCamera() #Im getting the error here!
    camera.resolution(2592, 1944)
    extraTime = 0
    numberoferrors = 0
    errors = 0
    while currentImage < self.numberOfImages:
      timestamp = int(time.time())
      timeleft = (numberOfImages - currentImage) * self.delay

      d = datetime.timedelta(seconds = timeleft)

      #print("DAYS:HOURS:MIN:SEC")
      #print("%d:%d:%d:%d" % (d.days-1, d.hour, d.minute, d.second))

      os.system('cls' if os.name == 'nt' else 'clear')
      print " ==================================="
      print " | Number of taken images: " + str(currentImage) + " |"
      print " |---------------------------------|"
      print " | Time left : " + str(d) 
      print " | Seconds left : " + str(timeleft) 
      if numberoferrors > 0:
        print " | Number of errors: " + str(numberoferrors)  
      print " ==================================="
      

      try:
        print "     | Warming upp camera |\n"
 
        # Warming upp camera
        camera.start_preview()
        time.sleep(2)

        # Creating the image after 2 sec of warmup
        camera.capture('images/' + str(timestamp) + '.jpg')
        #Shuting down camera to wait on the next image
        camera.stop_preview()
        # Add 1 to current image, to display and 
        # keep track of number of images created
        print "     |   Saved     |\n"
        currentImage += 1
        extraTime = 0
      except Exception as e:
        print e
        print "Error while trying to create: " + str(timestamp) + ".jpg"
        errors += 1
        numberoferrors += 1
        # If there is more than 5 errors the dilay will be 2x more
        if errors > 5:
          extraTime = self.delay
          errors = 0
          pass
        raise
      else:
        
        pass
      finally:

        pass


      try:
        print "Running delay on " + str(delay) + " S"
        print "Please hold!"
        timelaps2 = int(time.time())
        time.sleep( int(self.delay) - ( int(timelaps2) - int(timestamp) ) )
      except (KeyboardInterrupt, SystemExit):
        print "============================"
        print "| Shuting down script now! |"
        print "============================"
        currentImage = self.numberOfImages
        raise
      



#########################################################################################################
#########################################################################################################
#########################################################################################################

thread_capture = timelaps(delay, numberOfImages)


thread_capture.start()


thread_capture.join()

print "\n\n\nAll done !\n\n\n"
#########################################################################################################
#########################################################################################################
#########################################################################################################













