# Necessary packages to import
from sense_hat import SenseHat
import logging
import logzero
from logzero import logger
from picamera import PiCamera
import datetime
from time import sleep
from PIL import Image
import statistics
import ephem
import os

#Path to directory
dir_path = os.path.dirname(os.path.realpath(__file__))

#logging information
logzero.logfile(dir_path+"/data01.csv")
formatter = logging.Formatter('%(name)s - %(asctime)-15s - %(levelname)s: %(message)s');
logzero.formatter(formatter)

#getting geographical coordinates for each picture
name = "ISS (ZARYA)"
l1 = "1 25544U 98067A   19033.27351531  .00001422  00000-0  29623-4 0  9998"
l2 = "2 25544  51.6433 312.1797 0005043 343.6440 154.8135 15.53218636154298"
iss = ephem.readtle(name, l1, l2)


#obtaining a reference to Sense Hat

sh = SenseHat()

pb = (0, 80, 80)
y = (80, 80, 0)
b = (0, 0, 80)
n = (0,0,0)
g = (0,80,0)

#logo for in LED Matrix while Picamera is stopped

image = [
n,n,n,n,n,n,n,n,
n,g,g,g,g,g,n,n,
n,n,g,n,n,g,n,n,
n,n,g,n,n,g,n,n,
n,n,g,n,n,g,n,n,
n,g,g,n,n,g,n,n,
n,n,n,n,n,n,n,n,
n,n,n,n,n,n,n,n,
]


# Getting a PiCamera reference
cam = PiCamera()
cam.resolution = (1296, 972)
iss.compute()

#Obtaining longitude and Latitude for our picture
def get_latlon():
    iss.compute()
    long_value = [float(i) for i in str(iss.sublong).split(":")]
    if long_value[0]<0:
        long_value[0] = abs(long_value[0])
        cam.exif_tags['GPS.GPSLongitudeRef'] = "W"
    else:
        cam.exif_tags['GPS.GPSLongitudeRef'] = "E"
    cam.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])
        cam.exif_tags['GPS.GPSLatitudeRef'] = "S"
    else:
        cam.exif_tags['GPS.GPSLatitudeRef'] = "N"
    cam.exif_tags['GPS.GPSLatitude'] = '%d/1,%d/1,%d/10' % (lat_value[0], lat_value[1], lat_value[2]*10)
    return(str(lat_value), str(long_value))

#Making datetime variables (start/now) to compute when we finish taking pictures
start_time = datetime.datetime.now()
now_time= datetime.datetime.now()

#Counter to save the number of pictures
photo_counter = 1

#This is the core of the program. We get images while we're in the allowed time interval
#Once a picture is taken, the we choose some pixels and compute the amount of RED, GREEN and BLUE
#If the ratio totalblue/totalred is greater than 1.1 then we're over the sea; otherwise, we're over land
while (now_time<start_time + datetime.timedelta(minutes = 174)):
    try:
        #The name of our team is showed in the LED Matrix
        sh.show_message ("Go, 3.141592/'85 Go!",text_colour=y,back_colour=pb, scroll_speed=0.05)
        
        #Let's take a picture
        cam.capture(dir_path+"/photo_"+str(photo_counter).zfill(3)+".jpg")
        lat, lon = get_latlon()  
        
        #Let's convert the image to obtain RGB pixels
        imag = Image.open(dir_path+"/photo_"+str(photo_counter).zfill(3)+".jpg")
        imag = imag.convert("RGB")
        X,Y = 647,485
       
        pixelRGB = imag.getpixel((X,Y))
        R,G,B = pixelRGB
     
        red1 = R
        green1 = G
        blue1 = B


        X,Y = 300,300
       
        pixelRGB = imag.getpixel((X,Y))
        R,G,B = pixelRGB
        red2 = R
        green2 = G
        blue2 = B
    

        X,Y = 400,750
       
        pixelRGB = imag.getpixel((X,Y))
        R,G,B = pixelRGB
     
        red3 = R
        green3 = G
        blue3 = B

        X,Y = 480,260
       
        pixelRGB = imag.getpixel((X,Y))
        R,G,B = pixelRGB
     
        red4 = R
        green4 = G
        blue4 = B

        X,Y = 500,900
       
        pixelRGB = imag.getpixel((X,Y))
        R,G,B = pixelRGB
     
        red5 = R
        green5 = G
        blue5 = B

        X,Y = 800,400
       
        pixelRGB = imag.getpixel((X,Y))
        R,G,B = pixelRGB
     
        red6 = R
        green6 = G
        blue6 = B

        X,Y = 900,120
       
        pixelRGB = imag.getpixel((X,Y))
        R,G,B = pixelRGB
     
        red7 = R
        green7 = G
        blue7 = B

        X,Y = 700,800
       
        pixelRGB = imag.getpixel((X,Y))
        R,G,B = pixelRGB
     
        red8 = R
        green8 = G
        blue8 = B

        X,Y = 860,600
       
        pixelRGB = imag.getpixel((X,Y))
        R,G,B = pixelRGB
     
        red9 = R
        green9 = G
        blue9 = B 

        X,Y = 750,230
       
        pixelRGB = imag.getpixel((X,Y))
        R,G,B = pixelRGB
     
        red10 = R
        green10 = G
        blue10 = B

        #Once we've got all the RED, GREEN and BLUE we add up
        totalred=red1+red2+red3+red4+red5+red6+red7+red8+red9+red10
        totalgreen=green1+green2+green3+green4+green5+green6+green7+green8+green9+green10
        totalblue=blue1+blue2+blue3+blue4+blue5+blue6+blue7+blue8+blue9+blue10
        
        #Finally we check whether we're over the sea or not
        if totalblue/totalred > 1.1:
            logger.info("%s,%s,%s,SEA", photo_counter, lat, lon )
        else:
            logger.info("%s,%s,%s,LAND", photo_counter, lat, lon )
        
        #We set the inactive image, increase the pictures' counter and go to bed for 5 minutes
        sh.set_pixels(image)
        photo_counter +=1
        sleep(300)
        #Modifying current time
        now_time = datetime.datetime.now()

    except Exception as e:
        logger.error("An error ocurred: "+ srt(e))