# -*- coding: utf-8 -*-
"""
Created on Wed Aug 21 14:58:32 2019

@author: jamateos

Datos astrales para Ohathor

"""

import pandas as pd
import ephem
import datetime
import pytz
from math import degrees as deg


def Place_bdm():
    """ Localización y fecha """
    city = 'Boadilla del Monte'
    city_lon = '40.40460'
    city_lat = '-3.88469'
    city_elev = 682
    city_pressure = 0
    city_horizon = '0'
    date = datetime.datetime.utcnow()
    local = pytz.timezone('Europe/Madrid')
    local_date = local.localize(date)

    # Efemerides Inicio
    ephem.UTC = local
    home = ephem.Observer()
    home.lat, home.lon, home.elev = city_lon, city_lat, city_elev
    home.pressure, home.horizon = city_pressure, city_horizon
    home.date = date
    return home, city


def Place_cdt():
    """ Localización y fecha """
    city = 'Calzadilla de Tera'
    city_lon = '41.9748696'
    city_lat = '-6.1000505'
    city_elev = 750
    city_pressure = 0
    city_horizon = '0'
    date = datetime.datetime.utcnow()
    local = pytz.timezone('Europe/Madrid')
    local_date = local.localize(date)

    # Efemerides Inicio
    ephem.UTC = local
    home = ephem.Observer()
    home.lat, home.lon, home.elev = city_lon, city_lat, city_elev
    home.pressure, home.horizon = city_pressure, city_horizon
    home.date = date
    return home, city


def MoonPhaseName(home):
    """
    New Moon - Waxing Crescent - First Quarter - Waxing Gibbous
    Full Moon - Waning Gibbous - Last Quarter - Waning Crescent
    Human-readable names for phases of the moon, taken from:
    https://stackoverflow.com/questions/26702144/human-readable-names-for-phases-of-the-moon-with-pyephem/26707918
    """

    target_date_utc = home.date
    target_date_local = ephem.localtime(target_date_utc).date()
    next_full = ephem.localtime(ephem.next_full_moon(target_date_utc)).date()
    next_new = ephem.localtime(ephem.next_new_moon(target_date_utc)).date()
    next_last_quarter = ephem.localtime(ephem.next_last_quarter_moon(target_date_utc)).date()
    next_first_quarter = ephem.localtime(ephem.next_first_quarter_moon(target_date_utc)).date()
    previous_full = ephem.localtime(ephem.previous_full_moon(target_date_utc)).date()
    previous_new = ephem.localtime(ephem.previous_new_moon(target_date_utc)).date()
    previous_last_quarter = ephem.localtime(
        ephem.previous_last_quarter_moon(target_date_utc)).date()
    previous_first_quarter = ephem.localtime(
        ephem.previous_first_quarter_moon(target_date_utc)).date()
    if target_date_local in (next_full, previous_full):
        return 'Full-LLena: 100%'
    elif target_date_local in (next_new, previous_new):
        return 'New-Nueva: 0%'
    elif target_date_local in (next_first_quarter, previous_first_quarter):
        return 'First quarter-Cuarto Creciente: +50%'
    elif target_date_local in (next_last_quarter, previous_last_quarter):
        return 'Last quarter-Cuarto Menguante: -50%'
    elif previous_new < next_first_quarter < next_full < next_last_quarter < next_new:
        return 'Waxing crescent-Creciente: +0%...50%'
    elif previous_first_quarter < next_full < next_last_quarter < next_new < next_first_quarter:
        return 'Waxing gibbous-Creciente: +50%...100%'
    elif previous_full < next_last_quarter < next_new < next_first_quarter < next_full:
        return 'Waning gibbous-Menguante: -100%...50%'
    elif previous_last_quarter < next_new < next_first_quarter < next_full < next_last_quarter:
        return 'Waning crescent-Menguante: -50%...0%'


def MoonPhasesData(home):
    '''
    Datos de la luna
    '''

    format = "%Y-%m-%d %H:%M"
    #home.date = '2019/8/31 10:38:00'
    previous_new = ephem.previous_new_moon(home.date)
    previous_full = ephem.previous_full_moon(home.date)
    next_new = ephem.next_new_moon(home.date)
    next_full = ephem.next_full_moon(home.date)
    previous_firstQ = ephem.previous_first_quarter_moon(home.date)  # Q creciente
    next_firstQ = ephem.next_first_quarter_moon(home.date)
    previous_lastQ = ephem.previous_last_quarter_moon(home.date)  # Q menguante
    next_lastQ = ephem.next_last_quarter_moon(home.date)

    if previous_new > previous_full:  # Creciente
        d = float(home.date - previous_new)
        d_full = float(next_full - previous_new)  # días de creciente
        dx100 = d*100/d_full  # % la luna (+) creciente
    else:  # Menguante
        d = float(home.date - previous_full)
        d_new = float(next_new - previous_full)  # días de menguante
        dx100 = -(d_new-d)*100/d_new  # % la luna (-) menguante
        d = d+d_new  # días desde la luna nueva

    print("\nDate-time UTC: ", home.date)
    print('Date-time LOCAL: ', ephem.localtime(home.date).strftime(format))

    print("\nprevious new: ", previous_new)
    print('previous Q-first - Cuarto creciente: {}' .format(previous_firstQ))
    print("previous full: ", previous_full)
    print('previous Q-last - Cuarto menguante: {}' .format(previous_lastQ))

    print("\nnext new ", next_new)
    print('next Q-first - Cuarto creciente: {}' .format(next_firstQ))
    print("next full: ", next_full)
    print('next Q-last - Cuarto menguante: {}' .format(next_lastQ))

    print('\nMOON: {:05.02f} days  // {:.02f} %'.format(d, dx100))
    print('MOON Phase:  {}' . format(MoonPhaseName(home)))

    dict_html = ({
        'Luna nueva previa (utc)': str(previous_new),
        'Luna cuarto creciente previa (utc)': str(previous_firstQ),
        'Luna llena previa (utc)': previous_full,
        'Luna cuarto menguante previa (utc)': previous_lastQ,
        'Luna nueva siguiente  (utc)': next_new,
        'Luna cuarto creciente siguiente (utc)': next_firstQ,
        'Luna llena siguiente (utc)': next_full,
        'Luna cuarto menguante siguiente (utc)': next_lastQ,
        'Luna iluminación (%)': ('{:05.02f} días/days  // {:.02f} %'.format(d, dx100)),
        'Luna fase': ('{}' .format(MoonPhaseName(home))),
    })

    return dict_html


def Efemerides(place):
    """ Sacando las efemerides """
    home = place[0]
    city = place[1]
    #city = "Boadilla del Monte"
    format = "%Y-%m-%d %H:%M"
    sun, moon = ephem.Sun(), ephem.Moon()

    # SUN
    sun.compute(home)
    sun_azimuth = round(deg(float(sun.az)), 2)
    sun_altitude = round(deg(float(sun.alt)), 2)
    sunriseUTC = home.previous_rising(sun)
    sunsetUTC = home.next_setting(sun)
    sunrise = ephem.localtime(home.previous_rising(sun)).strftime(format)
    sunset = ephem.localtime(home.next_setting(sun)).strftime(format)

    # MOOON
    moon.compute(home)
    moon_azimuth = round(deg(float(moon.az)), 1)
    moon_altitude = round(deg(float(moon.alt)), 1)
    moon_illum = round(moon.phase, 1)
    moonriseUTC = home.next_rising(moon)
    moonsetUTC = home.next_setting(moon)
    moonrise = ephem.localtime(home.next_rising(moon)).strftime(format)
    moonset = ephem.localtime(home.next_setting(moon)).strftime(format)
    moon_phase = MoonPhaseName(home)
    full_moon = ephem.localtime(ephem.next_full_moon(home.date)).strftime(format)

    # Equinoxes & Solstices

    d1 = ephem.next_equinox(str(datetime.datetime.now().year))
    d1_p = ephem.previous_solstice(str(datetime.datetime.now().year))
    d2 = ephem.next_solstice(d1)
    d3 = ephem.next_equinox(d2)
    d4 = ephem.next_solstice(d3)

    # We relocate the horizon to get twilight times
    home.horizon = '-6'  # -6=civil twilight, -12=nautical, -18=astronomical
    dawn_twilightUTC = home.previous_rising(ephem.Sun(), use_center=True)  # Begin civil twilight
    dusk_twilightUTC = home.next_setting(ephem.Sun(), use_center=True)  # End civil twilight
    dawn_twilight = ephem.localtime(home.previous_rising(
        ephem.Sun(), use_center=True)).strftime(format)  # Begin civil twilight
    dusk_twilight = ephem.localtime(home.next_setting(
        ephem.Sun(), use_center=True)).strftime(format)  # End civil twilight

    print("\033[2J\033[1;1f")  # Límpia la pantalla de la consola
    print("\033[0;31m" + '------------- Datos astrales (ephem) ----------------' + '\033[0;m')
    print("\033[1;31m" + '\nCity:  ---      %s      ---' % city + '\033[0;m')
    print("date-time UTC: ", home.date)
    print("date-time LOCAL: ", ephem.localtime(home.date).strftime(format))
    print("date-time LOCAL-timezone: ", ephem.to_timezone(home.date, ephem.UTC))

    print("\033[3;31m" + '\n     Ephem:  --- SUN ---\033[0;m')
    print("sun  azimuth / altitude", sun_azimuth, sun_altitude)
    print("UTC sunrise / sunset", sunriseUTC, sunsetUTC)
    print("LOCAL sunrise / sunset", sunrise, sunset)
    print('UTC Crepúsculo del amanecer-dawn_twilight: {}'.format(dawn_twilightUTC))
    print('UTC Crepúsculo del anochecer-dusk_twilight: {}'.format(dusk_twilightUTC))
    print('LOCAL Crepúsculo del amanecer-dawn_twilight: {}'.format(dawn_twilight))
    print('LOCAL Crepúsculo del anochecer-dusk_twilight: {}'.format(dusk_twilight))

    print("\033[3;31m" + '\n     Ephem:  --- MOON ---\033[0;m')
    print("Moon  azimuth / altitude", moon_azimuth, moon_altitude)
    print("UTC moonrise / moonset", moonriseUTC, moonsetUTC)
    print("LOCAL moonrise / moonset", moonrise, moonset)
    print("moon illumination", moon_illum)
    print("moon phase", moon_phase)
    print("LOCAL next full moon", full_moon)

    print("\033[3;31m" + '\n     Ephem:  --- Equinoxes & Solstices ---\033[0;m')
    print('Equinoccio de primavera: ', d1)
    print('Solsticio de verano: ', d2)
    print('Equinoccio de otoño: ', d3)
    print('Solsticio de invierno: ', d4)
    print("Invierno: %.1f días" % (d1-d1_p))
    print("Primavera: %.1f días" % (d2-d1))
    print("Verano: %.1f días" % (d3-d2))
    print("Otoño: %.1f días" % (d4-d3))

    # Rellenamos el contexto para la plantilla
    dict_html = ({
        'Item': "Datos astrales",
        'Lugar': city,
        'Longitud (º)': str(home.lon),
        'Latitud (º)': str(home.lat),
        'Elevación (m/nivel mar)': str(home.elev),
        'Fecha-Hora (utc)': str(home.date),
        'Fecha-Hora (local)': str(ephem.localtime(home.date).strftime(format)),
        'Fecha-Hora (local)-Zona horaria': str(ephem.to_timezone(home.date, ephem.UTC)),
        'Sol azimut (º)': sun_azimuth,
        'Sol altitud (º)': sun_altitude,
        'Sol salida (utc)': sunriseUTC,
        'Sol ocaso (utc)': sunsetUTC,
        'Sol crepúsculo del amanecer (utc)': dawn_twilightUTC,
        'Sol crepúsculo del anochecer (utc)': dusk_twilightUTC,
        'Luna azimut (º)': moon_azimuth,
        'Luna altitud (º)': moon_altitude,
        'Luna salida (utc)': moonriseUTC,
        'Luna ocaso (utc)': moonsetUTC,
    })
    dict_html2 = ({
        'Equinoccio de primavera (utc)': d1,
        'Solsticio de verano (utc)': d2,
        'Equinoccio de otoño (utc)': d3,
        'Solsticio de invierno (utc)': d4,
        'Invierno': ("%.1f días/days" % (d1-d1_p)),
        'Primavera': ("%.1f días/days" % (d2-d1)),
        'Verano': ("%.1f días/days" % (d3-d2)),
        'Otoño': ("%.1f días/days" % (d4-d3))
    })

    dict_html.update(MoonPhasesData(home))
    dict_html.update(dict_html2)

    return dict_html


def SunMov(home):
    '''
    Azimut y elevación del sol las 24 horas
    '''
    d = home.date
    print("date-time UTC: ", d)
    d = home.date.triple()
    print("date-time UTC: ", d)
    d = home.date.tuple()
    print("date-time UTC: ", d)
    d = ephem.to_timezone(home.date, ephem.UTC)
    print("date-time TIMEZONE: ", d)


def carga_etiquetas(file_in):
    df = pd.read_csv(file_in, sep='\t', skiprows=0)
    df = df.reset_index(drop=True)  # Reset de indices
    return df


if __name__ == '__main__':
    print("\033[2J\033[1;1f")  # Límpia la pantalla de la consola
    print("\033[0;31m" + '--------- Datos astrales  (ephem) ------------' + '\033[0;m')
    contexto = Efemerides(Place_bdm())
    df = carga_etiquetas('S2.txt')
    lista = list(df['LABEL'])
    for k, v in contexto.items():
        print("%s \n %s" % (k, v))
        #contexto = { k : v ,}
        #print (contexto)
        if k in lista:
            print("Esta el bicho")
    # SunMov(home)
    #print (df['LABEL'])
