import ROGUE
import TAP_table_recording
import logger_setup
import mail_notification

DEBUGGING_MODE = True

if DEBUGGING_MODE:
	error_mailing_list = ["*****@*****.**"]
else:
	#error_mailing_list = ["*****@*****.**"]
	error_mailing_list = ["*****@*****.**", "*****@*****.**"]

# if already running, return
if os.popen("ps -Af").read().count(__file__) > 1:
	mail_notification.send_notification("ROGUE 2.0 code exited because it was already running", "ROGUE 2.0 code exited", error_mailing_list)
	sys.exit(0)

# create and set up filepath and directory for logs -
# log dir is subdir of script
if DEBUGGING_MODE:
	LOG_DIR = os.path.join(sys.path[0], "logs_debugging/run_ROGUE_2_and_TAP_recorder_log")
	if not os.path.exists(LOG_DIR):
		os.makedirs(LOG_DIR)
else:
	LOG_DIR = "/science/robonet/rob/Operations/Logs/2016"
LOG_NAME = "run_ROGUE_2_and_TAP_recorder_log"
LOG_DATE_TIME_FORMAT = "%Y-%m-%d"
logger = logger_setup.setup(__name__, LOG_DIR, LOG_NAME, LOG_DATE_TIME_FORMAT)

def run_ROGUE_and_TAP_recorder():
Purpose: Execute TAP_table_recording.py folllowed by ROGUE.py to record TAP table and then run microlensing survey page check 
"""

import sys
import os
import logging

import ROGUE
import TAP_table_recording
import logger_setup
import mail_notification

# if already running, return
if os.popen("ps -Af").read().count(__file__) > 1:
    mail_notification.send_notification(
        "ROGUE code exited because it was already running", "ROGUE code exited", ["*****@*****.**"]
    )
    sys.exit(0)

# create and set up filepath and directory for logs -
# log dir is subdir of script
# LOG_DIR = os.path.join(sys.path[0], "logs/run_ROGUE_and_TAP_recorder_log")
LOG_DIR = "/science/robonet/rob/Operations/Logs/2016"
LOG_NAME = "run_ROGUE_and_TAP_recorder_log"
LOG_DATE_TIME_FORMAT = "%Y-%m-%d"
logger = logger_setup.setup(__name__, LOG_DIR, LOG_NAME, LOG_DATE_TIME_FORMAT)


def run_ROGUE_and_TAP_recorder():
    logger.info("----------------------------------------------------------------")
    try:
def send_mail_notification(event):
    if check_if_event_has_been_mailed_before(event):
        logger.warning("Event has already been mailed before.")
        logger.warning("Aborting mail notification.")
        logger.debug("Event that had been mailed before: %s" % str(event))
        return

    """Send mail notification upon detecting short duration microlensing event"""
    """
	if DEBUGGING_MODE:
		notification_level = "Warning"
		notification_level_message = ""
	else:
		notification_level_dict = get_notification_level_and_message(event)
		notification_level = notification_level_dict["notification level"]
		notification_level_message = notification_level_dict["message"]
	"""
    notification_level_dict = get_notification_level_and_message(event)
    notification_level = notification_level_dict["notification level"]
    notification_level_message = notification_level_dict["message"]

    message_text = """\
Potential Short Duration Microlensing Event %s
%s

""" % (
        notification_level,
        notification_level_message,
    )

    if event.has_key("name_OGLE"):
        message_text += """\
OGLE Event Name: %s
OGLE Einstein Time: %s +/- %s
OGLE Event Page: %s

""" % (
            event["name_OGLE"],
            event["tE_OGLE"],
            event["tE_err_OGLE"],
            event["pageURL_OGLE"],
        )

    if event.has_key("name_MOA"):
        message_text += """\
MOA Event Name: %s
MOA Event ID: %s
MOA Einstein Time: %s +/- %s
MOA Event Page: %s

""" % (
            event["name_MOA"],
            event["ID_MOA"],
            event["tE_MOA"],
            event["tE_err_MOA"],
            event["pageURL_MOA"],
        )

        # The name used for reference, in the subject and summary page URL, is the OGLE event if available
        # Otherwise it is the MOA name
    if event.has_key("name_OGLE"):
        reference_event_name = event["name_OGLE"]
    elif event.has_key("name_MOA"):
        reference_event_name = event["name_MOA"]
    else:
        logger.warning("Event has neither MOA nor OGLE name.")
        logger.warning("Canceling mail notification.")
        return

    if event.has_key("name_ARTEMIS_OGLE"):
        message_text += """\
ARTEMIS OGLE Event Name: %s
ARTEMIS OGLE Einstein Time: %s +/- %s

""" % (
            event["name_ARTEMIS_OGLE"],
            event["tE_ARTEMIS_OGLE"],
            event["tE_err_ARTEMIS_OGLE"],
        )

    if event.has_key("name_ARTEMIS_MOA"):
        message_text += """\
ARTEMIS MOA Event Name: %s
ARTEMIS MOA Einstein Time: %s +/- %s

""" % (
            event["name_ARTEMIS_MOA"],
            event["tE_ARTEMIS_MOA"],
            event["tE_err_ARTEMIS_MOA"],
        )

    mail_subject = (
        "ROGUE: " + reference_event_name + " - Potential Short Duration Microlensing Event " + str(notification_level)
    )
    summary_page_URL = (
        "http://robonet.lcogt.net/temp/shortte_alerts/new_version_test/" + reference_event_name + "_summary.html"
    )
    message_text += """\
Event summary page: %s 

""" % (
        summary_page_URL
    )

    if DEBUGGING_MODE:
        tests = [
            "tE_test",
            "microlensing_assessment_MOA_test",
            "K2_microlensing_superstamp_region_test",
            "K2_microlensing_superstamp_region_alternate_test",
            "mag_test",
        ]
    else:
        tests = ["tE_test", "microlensing_assessment_MOA_test", "K2_microlensing_superstamp_region_test", "mag_test"]

    message_text += """\
Tests:
"""
    for test in tests:
        if event.has_key(test):
            message_text += """\
%s status: %s
""" % (
                test,
                event[test],
            )

    logger.debug("Mail notification text:\n%s" % message_text)
    try:
        mail_notification.send_notification(message_text, mail_subject, MAILING_LIST)
    except Exception as ex:
        logger.warning("Exception attempting to send mail notification.")
        logger.warning(ex)
        raise

    logger.info("Event notification mailed!")