import os
import glob
from pandas import read_csv
from pandas.errors import EmptyDataError
from fnmatch import filter 
from argparse import ArgumentParser
from tqdm import tqdm
from typing import List, Tuple
from epics import caget, caput
from datetime import datetime


def GlobSearchFile(args: Tuple[str, List[str]]) -> None:
    try:
        data = read_csv(args[0], usecols=[0], header=None, index_col=False, dtype=str)
        data = data[0].to_list()
        iocname = args[0].split('/')[-3]
        for count, pattern in enumerate(args[1]):
            deref = None
            if '.' in pattern: pattern, deref = pattern.split('.')
            found = filter(data, pattern)
            if bool(found):
                fname = f'temp_pv_list/{iocname}_{count}.txt'
                with open(fname, 'w') as file:
                    for variable in found:
                        file.write(f'{iocname},{variable}{("."+deref) if deref is not None else ""}\n')
            
        return
    except EmptyDataError:
        return

def EpicSnapshot(patterns: List[str], filename: str, pushfile: int) -> None:
    
    IOC_MACRO = os.environ.get('IOC_DATA')
    FILENAME = datetime.now().strftime('%b-%d-%Y-%I-%M%p') if filename is None else filename[0]
    
    if patterns[0] != "None":
        if not os.path.exists('temp_pv_list'):
            os.makedirs('temp_pv_list')
        else:
            os.system('rm temp_pv_list/*')
    
        files = glob.glob(f'{IOC_MACRO}/*/iocInfo/IOC.pvlist')
        files = list(set(files))

        print(f'\n\nSearching {len(files)} IOC:\n')
        for file in tqdm(files):
            GlobSearchFile((file, patterns))

        os.system('cat temp_pv_list/* > temp_pv_list/FINAL.txt')
        data = read_csv('temp_pv_list/FINAL.txt', header=None, dtype={'IOC': str, 'Key': str}, names=['IOC','Key'])
        data = data.sort_values(by=['IOC','Key'], ascending=[True, True])
        maxlen_key = data['Key'].str.len().max()

        print(f'\nResults [\033[94m{FILENAME}.txt\033[0m]:\n')
        with open(f'{FILENAME}.txt', 'w') as file:
            file.write('IOC,Key,Value\n')
            ioc_pre = "None"
            for _, row in data.iterrows():
                ioc, key = row['IOC'], row['Key']
                val = caget(key)
                if isinstance(val, (int, float)):
                    if ioc != ioc_pre:
                        ioc_pre = ioc
                        print(f'\n\033[94m{ioc}\033[0m')
                    val = float(val)
                    print(f'     {key.ljust(maxlen_key + 1)}: {val:+.5E}')
                    file.write(f'{ioc},{key},{val:+.5E}\n')
        os.system('rm -rf temp_pv_list')

    if bool(pushfile):
        for file in filename:
            if os.path.exists(f'{file}.txt'):
                data = read_csv(f'{file}.txt', dtype={'Key': str, 'Value': float})
                for _, row in data.iterrows():
                    try:
                        caput(row['Key'], row['Value'])
                        print(f'caput {row["Key"]} "{row["Value"]}"')
                    except:
                        print(f'Access to {row["Key"]} is Denied')
            else:
                print(f'Filename {file}.txt does not exist')

if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument('patterns', type=str, nargs='+')
    parser.add_argument('--filename', type=str, nargs='+', required=False, default=None)
    parser.add_argument('--pushfile', type=int, required=False, default=0)

    args = parser.parse_args()
    EpicSnapshot(args.patterns, args.filename, args.pushfile)
