import getpass
import os.path
import socket
import subprocess
import tempfile

import mgnt_utilities as utilities


class FacilityAgent:
    users = {
        'LCLS': 'softegr',
        'FACET': 'fsoftegr',
        'TestFac': getpass.getuser()
    }

    hosts = {
        'LCLS': 'lcls-srv01',
        'FACET': 'facet-srv01',
        'TestFac': 'testfac-srv01'
    }

    env_vars = {
        'LCLS': {
            'EPICS_IOCS': '/usr/local/lcls/epics/iocCommon',
            'IOC_DATA': '/u1/lcls/epics/ioc/data',
            'EDM': '/usr/local/lcls/tools/edm/display',
            'MGNT_REPORT': '/u1/lcls/epics/reports/Magnet'
        },
        'FACET': {
            'EPICS_IOCS': '/usr/local/facet/epics/iocCommon',
            'IOC_DATA': '/u1/facet/epics/ioc/data',
            'EDM': '/usr/local/facet/tools/edm/display',
            'MGNT_REPORT': '/u1/facet/epics/reports/Magnet'
        },
        'TestFac': {
            'EPICS_IOCS': '/afs/slac/g/acctest/epics/iocCommon',
            'IOC_DATA': '/nfs/slac/g/acctest/epics/ioc/data',
            'EDM': '/afs/slac/g/acctest/tools/edm/display',
            'MGNT_REPORT': '/nfs/slac/g/acctest/epics/report/Magnet'
        }
    }

    def __init__(self, facility):
        if not facility:
            if socket.gethostname() in self.users.values():
                # If in Prod, use current environment
                self.command_prefix = []
                self.user_host_prefix = ''
                self.remote_env = os.environ

            else:
                # Ask user to specify facility
                facility_list = ', '.join(self.hosts.keys())
                raise Exception(
                    'We are in Dev. Please specify one of the following facilities with -f: ' + facility_list)

        elif facility not in self.hosts:
            # In Dev but facility not supported
            raise ValueError('Facility {} is not supported')

        else:
            # In Dev and facility is supported
            user_host = '{}@{}'.format(self.users[facility], self.hosts[facility])
            self.command_prefix = ['ssh', '-x', user_host, '-o', 'BatchMode=yes']
            self.user_host_prefix = user_host + ':'
            env = self.env_vars[facility]
            self.remote_env = os.environ.copy()
            for var in env:
                self.remote_env[var] = env[var]

    def call_remote(self, command_args):
        call_args = self.command_prefix + command_args
        return subprocess.check_output(call_args, stderr=subprocess.STDOUT)

    def expand_vars(self, path):
        old_env = os.environ
        os.environ = self.remote_env
        result = os.path.expandvars(path)
        os.environ = old_env
        return result

    def read_file(self, path):
        full_path = self.expand_vars(path)
        return self.call_remote(['cat', full_path])

    def is_dir(self, path):
        full_path = self.expand_vars(path)
        try:
            self.call_remote(['env', '-i', '[ -d "{}" ]'.format(full_path)])
            return True

        except subprocess.CalledProcessError:
            return False

    def is_file(self, path):
        full_path = self.expand_vars(path)
        try:
            self.call_remote(['env', '-i', '[ -f "{}" ]'.format(full_path)])
            return True

        except subprocess.CalledProcessError:
            return False

    def get_files_containing_pattern(self, pattern, glob):
        full_glob = self.expand_vars(glob)
        try:
            out = self.call_remote(['grep', '-d', 'skip', '-lP', "'{}'".format(pattern), full_glob])
            return [os.path.basename(file_path) for file_path in out.splitlines()]

        except subprocess.CalledProcessError:
            return []

    def caput(self, pv, value):
        # utilities.warn_about_writes_if_enabled()
        if not utilities.enable_writes:
            raise CAException('Writing to {} is not allowed'.format(pv))

        return self.call_remote(['caput', pv, str(value)])

    def ping(self, host):
        return self.call_remote(['ping', '-c', '1', host])

    def rsync_to_remote(self, orig_path, dest_path):
        full_path = self.expand_vars(dest_path)
        subprocess.check_output(['rsync', '-a', orig_path, self.user_host_prefix + full_path])

    def write_file(self, data, path):
        with tempfile.NamedTemporaryFile(mode='w+t') as tf:
            tf.write(data + '\n')
            tf.flush()
            full_path = self.expand_vars(path)
            self.rsync_to_remote(tf.name, full_path)

    def ls_basenames(self, glob):
        full_glob = self.expand_vars(glob)
        try:
            out = self.call_remote(['ls', '-1', full_glob])
            return [os.path.basename(file_path) for file_path in out.splitlines()]

        except subprocess.CalledProcessError:
            return []


class CAException(Exception):
    def __init__(self, *args):
        super(CAException, self).__init__(*args)
        self.output = self.message
