import getpass
import os.path
import socket
import subprocess
import tempfile

from six import iteritems, itervalues

from . 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',
            'PYDM': '/usr/local/lcls/tools/pydm/display',
            'MGNT_REPORT': '/u1/lcls/epics/reports/Magnet',
            'DHCP': '/u1/lcls/sys/dhcp'
        },
        'FACET': {
            'EPICS_IOCS': '/usr/local/facet/epics/iocCommon',
            'IOC_DATA': '/u1/facet/epics/ioc/data',
            'EDM': '/usr/local/facet/tools/edm/display',
            'PYDM': '/usr/local/facet/tools/pydm/display',
            'MGNT_REPORT': '/u1/facet/epics/reports/Magnet',
            'DHCP': '/u1/lcls/sys/dhcp'
        },
        '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',
            'PYDM': '/afs/slac/g/acctest/tools/pydm/display',
            'MGNT_REPORT': '/nfs/slac/g/acctest/epics/report/Magnet',
            'DHCP': '/nfs/slac/g/cd/watchdogs/dhcp/dhcpweb'
        }
    }

    def __init__(self, facility):
        if not facility:
            # If in Prod, use current environment
            self.local_mode = True
            self.command_prefix = []
            self.user_host_prefix = ''
            # Temporary fix: set MGNT_REPORT manually
            self.remote_env = os.environ.copy()
            if socket.gethostname() in itervalues(self.hosts):
                facility = [key for key, value in iteritems(self.hosts) if value == socket.gethostname()][0]
                env = self.env_vars[facility]
                for var in env:
                    self.remote_env[var] = env[var]

        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
            self.local_mode = False
            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, shell=False):
        call_args = self.command_prefix + command_args
        return subprocess.check_output(call_args, stderr=subprocess.STDOUT, shell=shell).decode('utf-8')

    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:
            if self.local_mode:
                # Unsafe, please change this!
                self.call_remote(['env -i [ -d "{}" ]'.format(full_path)], shell=True)
            else:
                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:
            if self.local_mode:
                # Unsafe, please change this!
                self.call_remote(['env -i [ -f "{}" ]'.format(full_path)], shell=True)
            else:
                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:
            if self.local_mode:
                # Escape double quotes
                escaped_pattern = pattern.replace('"', '\\"')

                # Unsafe, please change this!
                out = self.call_remote(['grep -d skip -lP "{}" {}'.format(escaped_pattern, full_glob)], shell=True)
            else:
                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:
            if self.local_mode:
                # Unsafe, please change this!
                out = self.call_remote(['ls -1 {}'.format(full_glob)], shell=True)
            else:
                out = self.call_remote(['ls', '-1', '{}'.format(full_glob)])

            return [os.path.basename(file_path) for file_path in out.splitlines()]

        except subprocess.CalledProcessError:
            return []

    def get_full_name(self):
        user = utilities.get_user()
        slac_email = user + '@slac.stanford.edu'
        person_command = ['person', '-display', 'name', '-exact', '-match', 'email', slac_email]
        person_output = subprocess.check_output(person_command).decode('utf-8')
        person_lines = person_output.splitlines()
        if len(person_lines) < 4:
            full_name = user
        else:
            full_name = person_lines[3].strip()

        return full_name

    def get_screeniocs_entry(self, ioc_name):
        iocConsole_command = ['iocConsole', '-l', '-j', ioc_name]
        return self.call_remote(iocConsole_command)


class CAException(Exception):
    def __init__(self, *args):
        super(CAException, self).__init__(*args)
        self.output = self.message
