"""
Astro Pi Mission Space Lab 2019/2020
Submission from team SpaceChain (Austria)
Contact: Chris Baumann (mentor) c.baumann@baumann.at

---
The program works as follows:

Every 'loop_interval' (i.e. 15 seconds) the 'main loop' is called. It executes the following steps:

Step 1
* Calculate ISS position and height (using lib ephem).
* Write position and height to EXIF data of the (next) image.

Step 2
* Build the string "image_infos" and calculate the md5 hash of it, this will be used as the EXIF tag "ImageUniqueID".
* Build "annotate_text", this will be written to the image as overlay text.

Step 3
* Write step 2 information plus the sha256 hash value of the last image to EXIF data of the (next) image. This is "chaining" the images together (similar to a blockchain) and allows to detect, if an imagefile has been changed later.

Step 4
* Capture a new image and write it to disk.
* Calculate sha 256 hash value of the new image and keep it for next loop.

Step 5
* Write all relevant infos to the CSV data file.

Step 6
* Check, if max duration (3 hours) is reached; if yes, exit.
* Check, if max diskspace (3 GB) is exceeded (should not occur, but just in case); if yes, exit.

* Wait until next loop_time is reached,

"""

import os
import time
import csv
import hashlib
from datetime import datetime, timezone
from logzero import logger, logfile
import picamera
from ephem import readtle, degree
from random import randrange

# Latest TLE data for ISS location
# https://www.celestrak.com/NORAD/elements/stations.txt
ephem_name = "ISS (ZARYA)"
# last updated 9.2.2020
ephem_1 = "1 25544U 98067A   20040.38944444  .00001231  00000-0  30376-4 0  9996"
ephem_2 = "2 25544  51.6443 265.7441 0005014 245.2793  99.5753 15.49152210212043"

iss = readtle(ephem_name, ephem_1, ephem_2)

# Define constants and variables
team_name = 'SpaceChain';
dir_path = os.path.dirname(os.path.realpath(__file__))
log_file_name = dir_path + "/" + team_name + ".log"
data_file_name = dir_path + "/" + team_name + "_data.csv"
software_version = 'APMSL20 V1.1 Team ' + team_name

image_description = team_name + ': Hash value of previous image (sha256): '
artist_info = 'https://spacetoken.at/'

max_duration = 3 * 60 * 60 - 60 # 3 hours - 1 minute (in seconds)
max_diskspace = 3 * 1024 * 1024 * 1024 * 0.99 # 99 % of 3 GB (in bytes)

program_finished = False
loop_count = 0
loop_interval = 15 # seconds
sleep_interval = 0.1 # 1/10 sec

last_hash = 'n/a'
current_hash = 'n/a'

debug_console = False # write debug infos to console?

########## Helper functions

def format_time_utc_iso(time_to_convert):
  """
  Format a timestamp in seconds to ISO format using UTC as timezone.
  Example: 1581244077.0865223 will be formatted as 2020-02-09T10:27:57
  """
  return(datetime.fromtimestamp(time_to_convert, tz = timezone.utc).replace(microsecond = 0, tzinfo = None).isoformat())


def get_dir_size(dir_path):
  """ Calculate the total size of all files in a given directory (but not in its subdirectories!). """
  size = 0
  for f in os.listdir(dir_path):
    if os.path.isfile(f):
      size += os.path.getsize(f)
  if debug_console: print("dir_size: {} MB".format(size/1024/1024))
  return(size)


def create_csv_file(data_file):
  """ Create new CSV data file and write header. """
  with open(data_file, 'w') as f:
    writer = csv.writer(f)
    header = ("LoopCount", "DateTime", "Latitude", "Longitude", "Height", "eclipsed", "uniqueID", "lastHash", "currentHash")
    writer.writerow(header)


def add_csv_data(data_file, data):
  """ Add data to the CSV file. """
  if debug_console: print('data: ', data)
  with open(data_file, 'a') as f:
    writer = csv.writer(f)
    writer.writerow(data)


def get_latlon():
  """ Calculate ISS position and height using lib ephem, write it to EXIF data and return it. """
  iss.compute()
  # Set mandatory tag GPSVersionID (interpreted as 2.0.0.0)
  camera.exif_tags['GPS.GPSVersionID'] = '%d' % (2)
  # Set Long and Lat
  long_value = [float(i) for i in str(iss.sublong).split(":")]
  if long_value[0] < 0:
    long_value[0] = abs(long_value[0])
    camera.exif_tags['GPS.GPSLongitudeRef'] = "W"
  else:
    camera.exif_tags['GPS.GPSLongitudeRef'] = "E"
  camera.exif_tags['GPS.GPSLongitude'] = '%d/1,%d/1,%d/10' % (long_value[0], long_value[1], long_value[2]*10)
  lat_value = [float(i) for i in str(iss.sublat).split(":")]
  if lat_value[0] < 0:
    lat_value[0] = abs(lat_value[0])
    camera.exif_tags['GPS.GPSLatitudeRef'] = "S"
  else:
    camera.exif_tags['GPS.GPSLatitudeRef'] = "N"
  camera.exif_tags['GPS.GPSLatitude'] = '%d/1,%d/1,%d/10' % (lat_value[0], lat_value[1], lat_value[2]*10)
  # Set Altitude in meters above see level  
  camera.exif_tags['GPS.GPSAltitudeRef'] = '%d' % (0)
  camera.exif_tags['GPS.GPSAltitude'] = '%d/1' % (iss.elevation)
  # Return position etc. values
  return(iss.sublat / degree, iss.sublong / degree, iss.elevation, iss.eclipsed)


def capture_image(loop_count):
  """
  Capture image and save it to JPEG file, filename includes current loop_count. 
  Then calculate sha256 hash from saved file and return it.
  """
  image_file_name = dir_path + "/" + team_name + "_img_{0:03d}.jpeg".format(loop_count)
  if debug_console: print('capturing to file ', image_file_name)
  camera.capture(image_file_name)
  sha256_hash = sha256_file(image_file_name)
  return(sha256_hash)


def set_image_info(sha256_hash, unique_id, annotate_text):
  """ Set Exif-tags to include given information. """
  camera.exif_tags['EXIF.ImageUniqueID'] = unique_id
  camera.exif_tags['IFD0.ImageDescription'] = image_description + sha256_hash
  camera.exif_tags['IFD0.Artist'] = artist_info
  camera.exif_tags['IFD0.Software'] = software_version
  
  if annotate_text:
    camera.annotate_text = annotate_text
    camera.annotate_background = picamera.Color('black')


def sha256_file(file_name):
  """ Calculate SHA-256 hash of given file. """
  BUF_SIZE = 1048576
  sha256 = hashlib.sha256()
  with open(file_name, 'rb') as f:
    while True:
      data = f.read(BUF_SIZE)
      if not data:
        break
      sha256.update(data)
  sha256_hash = sha256.hexdigest()
  if debug_console: print('sha256 hash: ', sha256_hash)
  return(sha256_hash)


def md5_text(text):
  """ Calculate MD5 hash of a given text. """
  md5_hash = hashlib.md5(text.encode('utf-8')).hexdigest()
  if debug_console: print('md5 hash: ', md5_hash)
  return(md5_hash)


def random_exception(r):
  """ Generate an exception randomly by dividing through a random value in range 0..r """
  x = randrange(r)  
  if debug_console: print('random_exception: x: ', x)
  y = 1/x
  return(y)


########## Main program

if debug_console: 
  print('---------------------------')
  print(software_version + ' started ...')

# Setup logging and create data file
logfile(log_file_name)
create_csv_file(data_file_name)

# Setup camera and define resolution
camera = picamera.PiCamera()
camera.resolution = (2592, 1944) # max resolution for V1 camera = 5 MPixel
time.sleep(2) # camera warm-up

# Setup parameters for timing
start_time = time.time()
next_loop_time = start_time
end_time = start_time + max_duration

# Log infos about (planned) run time, maximum diskspace etc.
logger.info("Start at {} = {}".format(start_time, format_time_utc_iso(start_time)));
logger.info("end_time {} = {}".format(end_time, format_time_utc_iso(end_time)));
logger.info("max_diskspace {} bytes = {} MB".format(max_diskspace, max_diskspace/1024/1024));

"""
Main loop
Runs until max_duration is reached or max_diskspace is used.
"""
while not program_finished:
  try:
    time_now = time.time()
    time_now_utc_iso = format_time_utc_iso(time_now)
    
    if (time_now >= next_loop_time):
      next_loop_time = time_now + loop_interval
      
      # Test exception handling
      #random_exception(100)
  
      loop_count += 1
      logger.info("loop {}: {}".format(loop_count, time_now_utc_iso))
  
      # Step 1
      lat, lon, elevation, eclipsed = get_latlon()
      if debug_console: print('iss position, elevation[m], eclipsed: ', lat, lon, elevation, eclipsed)
      
      # Step 2      
      image_infos = "SpaceChain - Image {0:} - {1:} - Lat {2:.6f} - Long {3:.6f}".format(loop_count, time_now_utc_iso, lat, lon)
      unique_id = md5_text(image_infos)
      annotate_text = image_infos + '\nUniqueID ' + unique_id
      if debug_console: print('annotate_text: ', annotate_text)

      # Step 3
      set_image_info(last_hash, unique_id, annotate_text)	

      # Step 4
      current_hash = capture_image(loop_count)
  
      # Step 5
      data = (loop_count, time_now_utc_iso, lat, lon, elevation, eclipsed, unique_id, last_hash, current_hash)
      add_csv_data(data_file_name, data)
      
      last_hash = current_hash
  
      # Step 6
      # max_duration reached? => end main loop
      if (time_now >= end_time):
        program_finished = True
        logger.info("max_duration {} sec. reached, ending".format(max_duration))
  
      # max_diskspace reached? => end main loop
      if (get_dir_size(dir_path) > max_diskspace):
        program_finished = True
        logger.info("max_diskspace {} bytes reached, ending".format(max_diskspace));
  
      if debug_console: print('sleeping ...')
  
    if not program_finished:
      time.sleep(sleep_interval)
  
  except Exception as e:
    logger.error('Exception {}: {}'.format(e.__class__.__name__, e))
    
# cleanup
camera.close()
if debug_console: print('cleanup done, ending')
logger.info("End at {}".format(time_now_utc_iso));