#!/usr/bin/env python
#==============================================================
#
#  Abs:   Script for comparing barcodes and standardization
#         parameters between EPICS and Oracle
#
#  Name:  mgnt_stdz_compare
#
#  Usage: mgnt_stdz_compare.py [-h] [--email RECIPIENT]
#
#  Facility: SLAC Controls (Development)
#
#  Auth:  08-Jul-2020, A. Le (anle)
#--------------------------------------------------------------
#  Mods: (Latest to oldest)
#     23-Aug-2021, A. Le (anle)
#         Make script directory independent
#         Rename to mgnt_stdz_compare.py
#         Send report to user by default
#         Warn user if script is called from lcls-dev2 or lcls-dev3
#     13-Jul-2021, A. Le (anle)
#         Run caget_many once for all pvs
#         Add multithreading for pvcall
#     31-Aug-2020, A. Le (anle)
#         Clean up code
#     13-Aug-2020, A. Le (anle)
#         Add switch to send to different email
#     11-Aug-2020, A. Le (anle)
#         Adjust formatting
#         Use pyepics for caget
#         Add "not installed" column
#     27-Jul-2020, A. Le (anle)
#         Add logic for STDZDISABLE
#         Report total deferred and non-deferred magnets
#         -Add space between fail and missing sections
#         -Add message before stats table
#     17-Jul-2020, A. Le (anle)
#         Rename variables
#     15-Jul-2020, A. Le (anle)
#         Mark differing coefficients
#         Move templates to separate directory
#         Use IVB instead of POLYCOEF
#     14-Jul-2020, A. Le (anle)
#         Group devices by area
#         Report devices missing by area
#         Add table of missing magnets
#     13-Jul-2020, A. Le (anle)
#         Fix caget output
#         List device name and operational status
#     09-Jul-2020, A. Le (anle)
#         Take magnets from Oracle Infrastructure database
#
#==============================================================
#
import socket
import subprocess
import json
import os
import pwd
import smtplib
import epics
import argparse
from enum import Enum
from string import Template
from mgnt_get_elements import get_all_magnets
from email.mime.text import MIMEText
from collections import Counter, OrderedDict, defaultdict
from datetime import datetime
from itertools import product
from multiprocessing.dummy import Pool

TEMPLATE_DIR = 'templates'
TABLE_TEMPLATE = os.path.join(TEMPLATE_DIR, 'mgnt_fail_table.template')
MISSING_TEMPLATE = os.path.join(TEMPLATE_DIR, 'mgnt_missing_table.template')
STATS_TEMPLATE = os.path.join(TEMPLATE_DIR, 'mgnt_stats.template')
EMAIL_TEMPLATE = os.path.join(TEMPLATE_DIR, 'mgnt_stdz_email.template')

COLS = [
    ('BARCODE', 'BARCODE', 'Barcode'),
    ('STDZCYCLENUM', 'STDZCYCLENUM_VAL', 'Stdzcyclenum'),
    ('TRIMRAMPRATE', 'TRIMRAMPRATE_VAL', 'Trimramprate'),
    ('TRIMSETL', 'TRIMSETL_VAL', 'Trimsetl'),
    ('STDZDISABLE', '', '')
]

class Status(Enum):
    NOT_IN_EPICS = 1
    NOT_IN_ORACLE = 2
    NOT_MATCHING = 3
    MATCHING = 4

def caget(device, fields):
    try:
        pvs = ['{}:{}'.format(device, field) for field in fields]
        return epics.caget_many(pvs, timeout=0.5), True
    except epics.ca.ChannelAccessException as e:
        print(e)
        return ['-'] * len(fields), Status.NOT_IN_EPICS

def get_all_stdz_info(devices, fields):
    stdz_info_dict = defaultdict(dict)
    pvs = ['{}:{}'.format(device[2], field) for device, field in product(devices, fields)]
    stdz_info = epics.caget_many(pvs, timeout=5)
    for (device, field), inf in zip(product(devices, fields), stdz_info):
        stdz_info_dict[device[2]][field] = inf

    return stdz_info_dict
        
def pvcall(device, labels):
    pv_name = device + ':POLYALL'
    try:
        output = subprocess.check_output(['pvcall', '-w', '0.5', '-M', 'json', pv_name])
        data = json.loads(output)
        print data
        values = [data['value'][label][0] for label in labels]
        return values, True
    except subprocess.CalledProcessError as e:
        print(e.output)
        return ['-'] * len(labels), Status.NOT_IN_ORACLE
    except IndexError as e:
        print(e)
        return ['-'] * len(labels), Status.NOT_IN_ORACLE

def parallel_pvcall(devices, labels, processes=2):
    oracle_stdz_info = {}
    pvcall_func = lambda device: pvcall(device, labels)
    p = Pool(processes)
    for device, output in zip(devices, p.imap(pvcall_func, devices)):
        oracle_stdz_info[device] = output

    return oracle_stdz_info

def process_epics_stdz_info(ca_name, pvs, stdz_info_dict):
    inf = [stdz_info_dict[ca_name][pv] for pv in pvs]
    if None in inf[:-1]:
        return [], Status.NOT_IN_EPICS

    return inf, True

def compare_dev_pvs(device, cols, stdz_info_dict, oracle_stdz_info):
    print(device)
    pvs = [col[0] for col in cols]
    labels = [col[1] for col in cols[:-1]]
    ca_vals, ca_status = process_epics_stdz_info(device, pvs, stdz_info_dict)
    oracle_vals, oracle_status = oracle_stdz_info[device]
    if ca_status != Status.NOT_IN_EPICS and oracle_status != Status.NOT_IN_ORACLE:
        stdzdisable = ca_vals[-1]
        where_matching, status = mark_matching(ca_vals[:-1], oracle_vals, stdzdisable)
    elif oracle_status == Status.NOT_IN_ORACLE:
        where_matching = [False] * len(cols[:-1])
        status = oracle_status
    else:
        where_matching = [False] * len(cols[:-1])
        status = ca_status

    print(where_matching)
    return oracle_vals, ca_vals, where_matching, status

def mark_matching(ca_vals, oracle_vals, stdzdisable):
    oracle_ca_match = [is_matching(c, o) for c, o in zip(ca_vals, oracle_vals)]
    stdzcyclenum = oracle_vals[1]
    if stdzcyclenum <= 0 and stdzdisable == 1:
        oracle_ca_match[1] = True

    if all(oracle_ca_match):
        status = Status.MATCHING
    else:
        status = Status.NOT_MATCHING

    return oracle_ca_match, status

def is_matching(a, b):
    try:
        if type(a) in (int, float) and type(b) in (int, float):
            return float(a) == float(b)
        
        return a == b
    except ValueError as e:
        print(e)
        return a == b

def create_stats_table(areas, pass_counts, fail_counts, missing_counts, not_installed_counts):
    with open(STATS_TEMPLATE, 'r') as f:
        # Create row for each area
        area_stats = ''
        for area in areas:
            area_stats += '<tr><th>{}</th>'.format(area)
            for counts in [pass_counts, fail_counts, missing_counts, not_installed_counts]:
                area_stats += '<td>{}</td>'.format(counts[False][area] + counts[True][area])

            area_stats += '</tr>\n'

        total_def_stats = ''
        total_nondef_stats = ''
        total_stats = ''
        for counts in [pass_counts, fail_counts, missing_counts, not_installed_counts]:
            total_def_stats += '<td>{}</td>'.format(sum(counts[True].values()))
            total_nondef_stats += '<td>{}</td>'.format(sum(counts[False].values()))
            total_stats += '<td><b>{}</b></td>'.format(sum(counts[False].values()) + sum(counts[True].values()))
        
        # Generate stats table
        temp = f.read()
        table_temp = Template(temp)
        table = table_temp.substitute(
            area_stats=area_stats,
            total_def_stats=total_def_stats,
            total_nondef_stats=total_nondef_stats,
            total_stats=total_stats
        )
        return table

def create_fail_table(name, device, op_status, oracle_vars, db_vars, where_match):
    cols_th = ['<th>{}</th>'.format(col[2]) for col in COLS[:-1]]
    oracle_row = ''
    epics_row = ''
    for i in range(len(COLS[:-1])):
        if i >= len(oracle_vars):
            oracle_row += '<td></td>'
            epics_row += '<td class="diff">{}</td>'.format(db_vars[i])
        elif i >= len(db_vars):
            oracle_row += '<td class="diff">{}</td>'.format(oracle_vars[i])
            epics_row += '<td></td>'
        elif not where_match[i]:
            oracle_row += '<td class="diff">{}</td>'.format(oracle_vars[i])
            epics_row += '<td class="diff">{}</td>'.format(db_vars[i])
        else:
            oracle_row += '<td>{}</td>'.format(oracle_vars[i])
            epics_row += '<td>{}</td>'.format(db_vars[i])

    cols = ''.join(cols_th)
    with open(TABLE_TEMPLATE, 'r') as f:
        temp = f.read()
        table_temp = Template(temp)
        table = table_temp.substitute(
            name=name,
            device=device,
            op_status=op_status,
            cols=cols,
            oracle_row=oracle_row,
            epics_row=epics_row
        )
        return table

def create_fail_section(areas, fail_dict):
    fail_section = ''
    for area in areas:
        if fail_dict[area]:
            fail_section += '<hr>'
            fail_section += '<h3>{}</h3>'.format(area)
            for magnet in fail_dict[area]:
                fail_section += create_fail_table(*magnet)

    return fail_section

def create_missing_section(areas, missing_dict):
    missing_section = ''
    with open(MISSING_TEMPLATE, 'r') as f:
        temp = f.read()
        table_temp = Template(temp)
        for area in areas:
            if missing_dict[area]:
                magnet_rows = ''
                for name, device, op_status in missing_dict[area]:
                    magnet_rows += '<tr><th>{}</th>'.format(name)
                    magnet_rows += '<td>{}</td>'.format(device)
                    magnet_rows += '<td>{}</td></tr>\n'.format(op_status)

                table = table_temp.substitute(
                    area=area,
                    magnet_rows=magnet_rows
                )
                missing_section += table

        return missing_section

def create_email(fail_count, pass_fail_table, fail_elem_table, missing_elem_table):
    col_names = [col[2] for col in COLS]
    cols = ', '.join(col_names)
    with open(EMAIL_TEMPLATE, 'r') as f:
        temp = f.read()
        email_temp = Template(temp)
        timestamp = datetime.now().ctime()
        content = email_temp.substitute(
            timestamp=timestamp,
            fail_count=fail_count,
            cols=cols,
            pass_fail_table=pass_fail_table,
            fail_elem_table=fail_elem_table,
            missing_elem_table=missing_elem_table
        )
        return content

def send_email(facility, subject, message, sender, recipient):
    # Read config mgnt_email.cfg
    with open('mgnt_email.cfg', 'r') as f:
        email_config = json.load(f)

    msg = MIMEText(message, 'html')
    msg['Subject'] = '' + subject
    recipient_list = [recipient]
    msg['To'] = ','.join(recipient_list)
    msg['From'] = sender
    s = smtplib.SMTP(email_config['smtphost'])

    # Send email
    s.sendmail(sender, recipient_list, msg.as_string())
    s.quit()

def create_report():
    # Compare polynomial coefficients
    fail_elem_table = ''
    devices = get_all_magnets()
    ca_names = [device[2] for device in devices]
    fields = [col[0] for col in COLS]
    labels = [col[1] for col in COLS[:-1]]
    stdz_info_dict = get_all_stdz_info(devices, fields)
    oracle_stdz_info = parallel_pvcall(ca_names, labels)
    areas = OrderedDict()
    fail_dict = defaultdict(list)
    missing_dict = defaultdict(list)
    pass_counts = defaultdict(Counter)
    fail_counts = defaultdict(Counter)
    missing_counts = defaultdict(Counter)
    not_installed_counts = defaultdict(Counter)
    for device in devices:
        element, area, ca_name, op_status = device[:4]
        deferred = area.startswith('*')
        areas[area] = 1
        oracle_coeff, ca_coeff, where_matching, status = compare_dev_pvs(ca_name, COLS, stdz_info_dict, oracle_stdz_info)
        if status == Status.MATCHING:
            pass_counts[deferred][area] += 1
        elif status == Status.NOT_MATCHING:
            fail_dict[area].append((element, ca_name, op_status, oracle_coeff, ca_coeff, where_matching))
            fail_counts[deferred][area] += 1
        elif status in (Status.NOT_IN_EPICS, Status.NOT_IN_ORACLE):
            missing_dict[area].append((element, ca_name, op_status))
            missing_counts[deferred][area] += 1
        else:
            raise Exception('Unknown status:', status)
    
        if op_status.lower() == 'not installed' or not op_status:
            not_installed_counts[deferred][area] += 1
    
    fail_count = sum(fail_counts[False].values()) + sum(fail_counts[True].values())
    
    # Create email
    pass_fail_table = create_stats_table(areas, pass_counts, fail_counts, missing_counts, not_installed_counts)
    fail_elem_table = create_fail_section(areas, fail_dict)
    missing_elem_table = create_missing_section(areas, missing_dict)
    content = create_email(fail_count, pass_fail_table, fail_elem_table, missing_elem_table)

    return content

def get_user_email():
    user_details = pwd.getpwuid(os.getuid())
    return user_details.pw_name + "@slac.stanford.edu"

# Recommend mcclogin if user is on lcls-dev2 or lcls-dev3
hostname = socket.gethostname()
if hostname in ('lcls-dev2', 'lcls-dev3'):
    print 'WARNING: Please run this script on mcclogin instead of {} so that ' \
          'production PVs are readable.\n'.format(hostname)

# Parse arguments
user_email = get_user_email()
parser = argparse.ArgumentParser(description='Run magnet parameter comparison report. By default, the report is sent '
                                             "to the user's email ({}).".format(user_email))
parser.add_argument('--email', dest='recipient',
                    help='send the report to a different email')
parser.add_argument('--no-email', action='store_true',
                    help='run parameter comparison but do not send email (for testing only)')

args = parser.parse_args()

# Go to script directory
script_path = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))
os.chdir(script_path)

# Compare magnet parameters
content = create_report()
with open('email.html', 'w') as f:
    f.write(content)

# Send email
if not args.no_email:
    if args.recipient:
        recipient = args.recipient
    else:
        recipient = user_email

    send_email(None, 'Magnet Parameter Comparison Report', content, user_email, recipient)
