#!/usr/bin/env python
#==============================================================
#
#  Abs:   Script for checking MCOR types of magnets across
#         EPICS database, Oracle, and master list
#
#  Name:  mgnt_ps_compare.py
#
#  Usage: mgnt_ps_compare.py [-h] [--email RECIPIENT]
#
#  Facility: SLAC Controls (Development)
#
#  Auth:  31-Jul-2020, A. Le (anle)
#--------------------------------------------------------------
#  Mods: (Latest to oldest)
#     23-Aug-2021, A. Le (anle)
#         Make script directory independent
#         Rename to mgnt_ps_compare.py
#         Send report to user by default
#         Warn user if script is called from lcls-dev2 or lcls-dev3
#     14-Jul-2021, A. Le (anle)
#         Add multithreading for pvcall
#         Read MCOR types from channel access
#     31-Aug-2020, A. Le (anle)
#         Clean up code
#     05-Aug-2020, A. Le (anle)
#         Get area from control system name
#         Include MCOR types in missing section
#         -Use eget to retrieve EPICS PVs
#         -Add option to log eget fails
#     04-Aug-2020, A. Le (anle)
#         Infer area from device name if not in Oracle
#         Change header names to EPICS, Oracle, and Master
#         Shrink area headers
#         Add timestamp
#         Add MCOR PVs in totals
#         Add switch to send to different email
#
#==============================================================
#
import csv
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 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_ps_missing_table.template')
STATS_TEMPLATE = os.path.join(TEMPLATE_DIR, 'mgnt_ps_stats.template')
EMAIL_TEMPLATE = os.path.join(TEMPLATE_DIR, 'mgnt_ps_email.template')

MCOR_FLAVORS = [1, 2, 6, 12, 30]

COLS = [
    'Element',
    'Control System Name',
    'MCOR PV',
    'EPICS',
    'Oracle',
    'Master'
]

class Status(Enum):
    NOT_IN_MASTER = 1
    NOT_IN_ORACLE = 2
    MISSING = 3
    NOT_MATCHING = 4
    MATCHING = 5

def get_mcor_magnets(magnets):
    mcor_magnets = []
    mcor_magnets_temp = []
    mcor_type_pvs = []
    for magnet in magnets:
        if magnet[4] in ('EMCOR', 'MCOR'):
            mcor_magnets_temp.append(magnet)
            mcor_type_pvs.append(magnet[5] + ':TYPE')

    mcor_type_nums = epics.caget_many(mcor_type_pvs, timeout=2)
    for magnet, type_num in zip(mcor_magnets_temp, mcor_type_nums):
        try:
            flavor = MCOR_FLAVORS[type_num - 1]
            mcor_type = 'MCOR' + str(flavor)
        except (IndexError, TypeError) as e:
            print(e)
            mcor_type = '-'

        mcor_magnets.append((
            magnet[0], # element
            magnet[1], # area
            magnet[2], # device
            magnet[5], # mcor name
            mcor_type # mcor type
        ))

    return mcor_magnets

def load_epics_magnets():
    global epics_magnets
    epics_magnets = []
    with open('ps_lists/epics_list') as f:
        reader = csv.DictReader(f)
        for row in reader:
            if row['Device']:
                area = get_area(row['Device'])
            else:
                area = get_area(row['Name'])

            # Exclusions
            mag_type = get_type(row['Device'])
            if mag_type not in ('SOLN', 'BEND', 'BTRM', 'XCOR', 'YCOR', 'QUAD', 'SEXT', 'LGPS') or area in ('L0B', 'L1B', 'L2B', 'L3B'):
                continue

            epics_magnets.append((
                row['Element'],
                area,
                row['Device'],
                row['Name'],
                row['Type']
            ))

def load_master_magnets():
    global master_magnets
    master_magnets = {}
    with open('ps_lists/mgnt_master_list') as f:
        reader = csv.reader(f)
        for row in reader:
            element, ma_type = row
            master_magnets[element] = ma_type

def get_type(device):
    fields = device.split(':')
    if not fields:
        return 'UNKNOWN'

    return fields[0]

def get_area(device):
    fields = device.split(':')
    if len(fields) < 2:
        return 'UNKNOWN'

    return fields[1]

def master_type(element):
    if element not in master_magnets:
        return '-', Status.NOT_IN_MASTER

    return master_magnets[element], True

def oracle_type(device):
    pv_name = device + ':POLYALL'
    try:
        output = subprocess.check_output(['pvcall', '-w', '0.5', '-M', 'json', pv_name])
        data = json.loads(output)
        fields = ['IMIN_VAL', 'IMAX_VAL']
        values = data['value']
        imin = values['IMIN_VAL'][0]
        imax = values['IMAX_VAL'][0]
        abs_max = max(abs(imin), abs(imax))
        flavor = min(f for f in MCOR_FLAVORS if f >= abs_max)
        return 'MCOR' + str(flavor), True
    except subprocess.CalledProcessError as e:
        print(e.output)
        return '-', Status.NOT_IN_ORACLE
    except IndexError as e:
        print(e)
        return '-', Status.NOT_IN_ORACLE

def parallel_oracle_type(devices, processes=2):
    oracle_mcor_type = {}
    p = Pool(processes)
    for device, output in zip(devices, p.imap(oracle_type, devices)):
        oracle_mcor_type[device] = output

    return oracle_mcor_type


def compare_type(element, device, ca_type, oracle_mcor_type):
    or_type, or_status = oracle_mcor_type[device]
    ma_type, ma_status = master_type(element)
    if ma_status == Status.NOT_IN_MASTER:
        status = Status.MISSING
    elif ca_type != ma_type or or_type != ma_type:
        status = Status.NOT_MATCHING
    else:
        status = Status.MATCHING

    return ma_type, or_type, status

def create_stats_table(areas, pass_counts, fail_counts, missing_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]:
                area_stats += '<td>{}</td>'.format(counts[area])

            area_stats += '</tr>\n'

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

def create_fail_table(magnets):
    fail_table = '<table>\n'
    header = '<thead>\n'
    header += '<tr>'
    for col in COLS:
        header += '<th>{}</th>'.format(col)

    header += '</tr>\n'
    header += '</thead>\n'
    fail_table += header
    fail_table += '<tbody>\n'
    for magnet in magnets:
        name, device, mcor, ca_type, or_type, ma_type = magnet
        row = '<tr>'
        row += '<td>{}</td>'.format(name)
        row += '<td>{}</td>'.format(device)
        row += '<td>{}</td>'.format(mcor)
        if ca_type != ma_type:
            row += '<td class="diff">{}</td>'.format(ca_type)
        else:
            row += '<td>{}</td>'.format(ca_type)

        if or_type != ma_type:
            row += '<td class="diff">{}</td>'.format(or_type)
        else:
            row += '<td>{}</td>'.format(or_type)

        row += '<td><b>{}</b></td>'.format(ma_type)
        row += '</tr>\n'
        fail_table += row

    fail_table += '</tbody>\n'
    fail_table += '</table>'
    return fail_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)
            fail_section += create_fail_table(fail_dict[area])

    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, mcor, ca_type, or_type in missing_dict[area]:
                    magnet_rows += '<tr>\n'
                    magnet_rows += '<th>{}</th>'.format(name)
                    magnet_rows += '<td>{}</td>'.format(device)
                    magnet_rows += '<td>{}</td>'.format(mcor)
                    if ca_type != or_type:
                        magnet_rows += '<td class="diff">{}</td>'.format(ca_type)
                        magnet_rows += '<td class="diff">{}</td></tr>\n'.format(or_type)
                    else:
                        magnet_rows += '<td>{}</td>'.format(ca_type)
                        magnet_rows += '<td>{}</td></tr>\n'.format(or_type)

                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_count, missing_elem_table):
    cols = ', '.join(COLS)
    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_count=missing_count,
            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():
    fail_elem_table = ''
    devices = get_all_magnets()
    epics_magnets = get_mcor_magnets(devices)
    mcor_names = [device[2] for device in epics_magnets]
    oracle_mcor_type = parallel_oracle_type(mcor_names)
    areas = OrderedDict()
    fail_dict = defaultdict(list)
    missing_dict = defaultdict(list)
    pass_counts = Counter()
    fail_counts = Counter()
    missing_counts = Counter()
    for name, area, device, mcor, ca_type in epics_magnets:
        areas[area] = 1
        ma_type, or_type, status = compare_type(name, device, ca_type, oracle_mcor_type)
        if status == Status.MATCHING:
            pass_counts[area] += 1
        elif status == Status.NOT_MATCHING:
            fail_dict[area].append((name, device, mcor, ca_type, or_type, ma_type))
            fail_counts[area] += 1
            print name, device
            print 'EPICS:', ca_type
            print 'Oracle:', or_type
            print 'Master:', ma_type
        elif status == Status.MISSING:
            missing_dict[area].append((name, device, mcor, ca_type, or_type))
            missing_counts[area] += 1
        else:
            raise Exception('Unknown status:', status)
    
    fail_count = sum(fail_counts.values())
    print 'Number of bad devices:', fail_count
    
    # Create email
    pass_fail_table = create_stats_table(areas, pass_counts, fail_counts, missing_counts)
    fail_elem_table = create_fail_section(areas, fail_dict)
    missing_count = sum(missing_counts.values())
    missing_elem_table = create_missing_section(areas, missing_dict)
    content = create_email(fail_count, pass_fail_table, fail_elem_table, missing_count, 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 MCOR type 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 MCOR type 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)

# Load device lists
load_master_magnets()

# Compare MCOR types
content = create_report()

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

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