#!/usr/bin/env python
# -*- Encoding: utf-8 -*-
#
# Very rough module to get meteo data from the IRiS meteo station.
# L. Le Guillou, 2018-01-03

#------------------------------------------------------------------------------------------

"""

IRiS Meteo module

A very rough module to get some meteo data from the IRiS meteo station,
through its website http://iris.lam.fr/ .

Disclaimer: do not use this for telescope safety, as any web/network problem
may affect the results.

"""

#------------------------------------------------------------------------------------------

import sys, os, os.path
import time
import re

# import mx.DateTime
import datetime
from astropy.time import Time
import pytz
cet = pytz.timezone('CET')
def convert_date(date, time):
    d, m, y = list(map(int, date.split('/')))
    h, min, s = list(map(int, time.split(':')))
    t = datetime.datetime(y, m, d, h, min, s, 0, cet)
    return Time(t)
#------------------------------------------------------------------------------------------

from io import StringIO
#import Image

import urllib.request, urllib.error, urllib.parse
# import urllib
# from cookielib import CookieJar

# Timezone -> Pb.........................

#------------------------------------------------------------------------------------------

prefix = 'http://iris.lam.fr/wp-includes/images/ftp_iris'

txheaders =  {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/18.0',
              'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
              'Accept-Language': 'fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3',
              'Accept-Encoding': 'gzip, deflate'
}

# cj = None
# opener = None

#------------------------------------------------------------------------------------------

# def connect():
#     # Identification (login)
#     cj = CookieJar()
#     opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
#     urllib2.install_opener(opener)

#     # theurl = 'http://www.google.co.uk/search?hl=en&ie=UTF-8&q=voidspace&meta='
#     # txdata = None
#     theurl = prefix + '/'
#     # theurl = 'http://localhost/'
#     # txdata = urllib.urlencode( \
#         #     { "user" : username, "password": password } )
#     txdata="user=%s&pass=%s" % (username, password)
#     req = urllib2.Request(theurl, txdata, txheaders)
#     handle = urllib2.urlopen(req)
#     content = handle.read()


#------------------------------------------------------------------------------------------

def get_humidity():
    """
    Récupère l'humidité mesurée par la station météo d'IRiS.
    """

    # 12/12/2017,12:15:53,78,79.8
    
    theurl = prefix + '/humidity.data'
    txdata=""
    req = urllib.request.Request(theurl, txdata, txheaders)
    handle = urllib.request.urlopen(req)
    if not(handle): return None
    content = handle.read()
    if not(content): return None

    lines = re.split("\r\n+", content)
    lines.reverse()
    for line in lines:
        print(line)
        parts = line.strip().split(",")
        print(parts)
        if len(parts) < 4:
            continue
        s_date = parts[0]
        s_time = parts[1]
        s_hum1 = parts[2]
        s_hum2 = parts[3]

        # print s_date, s_time, s_hum1, s_hum2
        d = mx.DateTime.DateTimeFrom(s_date, s_time + " CET")
        hum1 = float(s_hum1)
        hum2 = float(s_hum2)
        return {'date': d, 'humidity 1': hum1, 'humidity 2': hum2}

    return None
    
#------------------------------------------------------------------------------------------

def get_temperature():
    """
    Récupère la/les températures mesurées (°C) par IRiS, ainsi que le point de rosée calculé.
    """

    #                     Ext1,Ext2 ..., ...., pdrosée ext, pd rosée coupole IRiS 
    # 13/12/2017,04:41:42,1.4,-0.7, 04.50,2.9,-6.7,-5.5
    
    theurl = prefix + '/temperature.data'
    txdata=""
    req = urllib.request.Request(theurl, txdata, txheaders)
    handle = urllib.request.urlopen(req)
    if not(handle): return None
    content = handle.read()
    if not(content): return None

    lines = re.split("\r\n+", content)
    lines.reverse()
    for line in lines:
        print(line)
        parts = line.strip().split(",")
        print(parts)
        if len(parts) < 8:
            continue
        s_date = parts[0]
        s_time = parts[1]
        s_ext1 = parts[2]
        s_ext2 = parts[3]
        s_pdr_ext = parts[6]

        # print s_date, s_time, s_hum1, s_hum2
        #d = mx.DateTime.DateTimeFrom(s_date, s_time + " CET")
        d = convert_date(s_date, s_time)
        ext1 = float(s_ext1)
        ext2 = float(s_ext2)
        pdr_ext = float(s_pdr_ext)
        return {'date': d, 'temp ext 1': ext1, 'temp ext 2': ext2, 'dew point': pdr_ext }

    return None
    
#------------------------------------------------------------------------------------------

def get_pressure():
    """
    Récupère la pression atmosphérique (hPa) mesurée par la station météo d'IRiS.
    """

    # 09/01/2018,17:26:24,10.1,10.8,1

    theurl = prefix + '/pressure.data'
    txdata=""
    req = urllib.request.Request(theurl, txdata, txheaders)
    handle = urllib.request.urlopen(req)
    if not(handle): return None
    content = handle.read()
    if not(content): return None

    lines = re.split("\r\n+", content)
    lines.reverse()
    for line in lines:
        print(line)
        parts = line.strip().split(",")
        print(parts)
        if len(parts) < 3:
            continue
        s_date = parts[0]
        s_time = parts[1]
        s_pressure = parts[2]

        # print s_date, s_time, s_hum1, s_hum2
        #d = mx.DateTime.DateTimeFrom(s_date, s_time + " CET")
        d = convert_date(s_date, s_time)
        pressure = float(s_pressure)
        return {'date': d, 'pressure': pressure}

    return None
    
#------------------------------------------------------------------------------------------

STATUS_RAIN         = 0
STATUS_CLEAR_SKY    = 1
STATUS_CLOUDY       = 2
STATUS_VERY_CLOUDY  = 3

def get_wind_and_clouds():
    """
    Récupère la vitesse du vent (km/h) mesurée par la station météo d'IRiS, 
    ainsi que l'état du ciel :
      clouds = STATUS_RAIN = 0         statut inconnu (pluie détectée)
      clouds = STATUS_CLEAR_SKY = 1    ciel clair
      clouds = STATUS_CLOUDY = 2       ciel un peu nuageux
      clouds = STATUS_VERY_CLOUDY = 3  ciel très nuageux (IRiS ferme)

    """
    #       CloudCondBolt = 0 si statut inconnu (pluie détectée), 1 si
    #       ciel clair, 2 si ciel un peu nuageux et 3 si ciel très
    #       nuageux (on ferme).
    
    # - Le fichier wind.data sauve le vent:
    #       OutData = Date+ »,"+Time+","+WindBolt+","+WindValueAAG+","+CloudCondBolt+"\n"
    #       La vitesse est en km/h

    theurl = prefix + '/wind.data'
    txdata=""
    req = urllib.request.Request(theurl, txdata, txheaders)
    handle = urllib.request.urlopen(req)
    if not(handle): return None
    content = handle.read()
    if not(content): return None

    lines = re.split("\r\n+", content)
    lines.reverse()
    for line in lines:
        print(line)
        parts = line.strip().split(",")
        print(parts)
        if len(parts) < 5:
            continue
        s_date = parts[0]
        s_time = parts[1]
        s_wind_bolt = parts[2]
        s_wind_aag = parts[3]
        s_cloud_cond_bolt = parts[4]

        # print s_date, s_time, s_hum1, s_hum2
        #d = mx.DateTime.DateTimeFrom(s_date, s_time + " CET")
        d = convert_date(s_date, s_time)
        wind_bolt = float(s_wind_bolt)
        wind_aag  = float(s_wind_aag)
        cloud_cond_bolt = int(s_cloud_cond_bolt)
        return {'date': d,
                'wind speed Boltwood II': wind_bolt,
                'wind speed AAG': wind_aag,
                'clouds': cloud_cond_bolt }

    return None
    
#------------------------------------------------------------------------------------------

def get_allskycam():
    """
    Récupère la dernière image de la caméra all-sky d'IRiS (objet PIL/Image).
    """
    import Image
    theurl = prefix + '/skyeye.jpg'
    txdata=""
    req = urllib.request.Request(theurl, txdata, txheaders)
    handle = urllib.request.urlopen(req)
    if not(handle): return None
    content = handle.read()
    if not(content): return None

    img = Image.open(StringIO(content))

    return img
    
#------------------------------------------------------------------------------------------

