from ats.topology import Testbed, Device

import re
import sys
import logging
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)

class nso_utils(object):
    def __init__(self,
                 mgmt_ip,
                 username,
                 password):
        self.mgmt_ip = mgmt_ip
        self.username = username
        self.password = password
        try:
            self.dut = Device(name = 'laas-nxv', \
                          type = 'linux', \
                          tacacs = { \
                                    'username' : '{0}'.format(self.username) \
                          }, \
                          passwords = { \
                                    'linux' : '{0}'.format(self.password) \
                          }, \
                          connections = { \
                                    'linux' : { \
                                        'protocol' : 'ssh', \
                                        'ip' : '{0}'.format(self.mgmt_ip) \
                                    } \
                          })
            self.dut.connect()
            self.dut.execute('uname -a')
            self.dut.execute('cd /auto/kdp-nxos/nso/run-nso')
            self.dut.execute('source ../nso/ncsrc')
            self.dut.execute('pwd')
            self.dut.transmit ("ncs_cli -C -u admin\r")
            self.dut.receive('nopattern^',timeout=1)
            self.dut.transmit("config")
            self.dut.receive('nopattern^',timeout=1)
            self.dut.transmit("devices device sim10")
            self.dut.receive('nopattern^',timeout=1)
            self.dut.transmit("config")
            self.dut.receive('nopattern^',timeout=1)
        except:
            log.error("Unexpected error: Connection to NSO Device failed. "\
                                , sys.exc_info()[0])

    def transmit_file_contents(self,
                               filename):
        with open(filename, mode='r') as f:
            data = f.read()
        self.dut.transmit(data)
        self.dut.receive('nopattern^',timeout=1)

    def get_payload(self, 
                    filename):
        self.transmit_file_contents(filename)
        self.dut.transmit("commit dry-run outformat native | save /auto/kdp-nxos/payloads/nso_payload")
        self.dut.receive('nopattern^',timeout=1)
        output = self.dut.receive_buffer()
        match = re.search('File already exists', output)
        match = str(match)
        if match != 'None':
            self.dut.transmit("yes\r")
            self.dut.receive('nopattern^',timeout=1)

        self.dut.transmit("exit")
        self.dut.receive('nopattern^',timeout=1)
        self.dut.transmit("exit")
        self.dut.receive('nopattern^',timeout=1)
        self.dut.transmit("exit")
        self.dut.receive('nopattern^',timeout=2)
        output2 = self.dut.receive_buffer()
        match2 = re.search('Uncommitted changes found', output2)
        match2 = str(match2)
        if match2 != 'None':
            self.dut.transmit("no\r")
            self.dut.receive('nopattern^',timeout=1)
        self.dut.transmit("exit")
        self.dut.receive('nopattern^',timeout=1)
        self.dut.transmit("cat /auto/kdp-nxos/payloads/nso_payload")
        self.dut.receive('nopattern^',timeout=1)
        out = self.dut.receive_buffer()
        self.dut.transmit("exit")
        self.dut.receive('nopattern^',timeout=1)
        out = '\n'.join(out.split('\n')[11:-4])
        return out.strip()

    def __del__(self):
        self.dut.disconnect()
