##################################
# ssh_commands.py                #
# Developed by: M. Graham Macy   #
# Created: 12/03/24              #
# Last Updated: 12/03/24         #
##################################

import subprocess
import sys
import paramiko
import tkinter as tk
from tkinter import filedialog
import paramiko
import subprocess
import survey
import time

class ssh_cmd():

    '''
    This is a class which holds ssh commands for Turkey

    '''
    def __init__(self):
        return

    def ssh_package_install():
        # makes sure that necessary packages are pip installed
        print('Making sure this computer has all required packages inst...')
        required_packages = ['paramiko', 'survey']
        for package in required_packages:
            subprocess.check_call([sys.executable, '-m', 'pip', 'install', package])

    def systel_login(password):
        print("Attempting to SSH into Mk1 Systel...")
        hostname = '10.52.15.17'
        username = 'hermeus'
        password = password
        success = False
        while success == False:
            try:
                ssh = paramiko.SSHClient()
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                ssh.connect(hostname=hostname, username=username, password=password)
                success = True
            except:
                print("Something didn't work. Make sure you have paramiko installed.")
                print("Did you type in the correct password?")
                success = False
        return ssh

    def stop_data_recorder(ssh):
        # stop data recording if queryer answers yes
        stopyn = input("Stop data recording? Type 'y' for yes, type any key for no: ")
        if stopyn == 'y':
            print("Stopping Systel Data Recorder")
            stdin, stdout, stderr = ssh.exec_command('sudo service recorder stop')
            output = stdout.read().decode()
            print(output)

    def start_data_recorder(ssh):
        # starts data recorder
        print("Starting Data Recorder")
        # Start the data recorder again query
        startdata_yn = input("Start data recorder? (Do this if Mk1 is not going to cycle LV before a test) - type 'y' if yes: ")
        if startdata_yn == 'y':
            try:
                stdin, stdout, stderr = ssh.exec_command('sudo service recorder start')
                print("Data recorder has been started again.")
            except:
                print("Something went wrong.")

    def systel_space(ssh):
        # space left on data recorder
        stdin, stdout, stderr = ssh.exec_command('df')
        output = stdout.read().decode()
        print(output)

    def list_files(ssh):
        stdin, stdout, stderr = ssh.exec_command('ls')
        systelfiles = stdout.read().decode()
        print(systelfiles)
        return systelfiles

    def get_pcaps(ssh,systelfiles):

        # choose the files you want
        pcap_files = []
        opt = systelfiles
        indexes = list(survey.routines.basket("Choose a file or start typing a date: ",options=opt))
        for item in indexes:
            pcap_files.append(opt[item])
        print(f"You selected: {pcap_files}")

        # copy files to designated location
        # assign a directory for those files
        directory = filedialog.askdirectory(title="Select a Directory for the pcap file to go into")
        print("You have chosen: ", directory)

        # Open SFTP client
        sftp = ssh.open_sftp()

        # for each pcap you chose...
        for file in pcap_files:
            # Specify the remote file path and local file path
            remote_file_path = pcap_files[file]
            local_file_path = directory

            # Copy file from remote to local
            sftp.get(remote_file_path, local_file_path)
            print('Copying pcap from remote location to local directory...')

        rm_yn = input("Remove copied files from systel? (WARNING: Upload these files to S3 if you plan to remove them) - type 'y' if yes: ")
        if rm_yn == 'y':
            print("You opted to remove the files from the systel.")
            for filename in pcap_files:
                stdin, stdout, stderr = ssh.exec_command('rm' + filename)
        else:
            print("You opted not to remove the files from the systel.")


        # Close terminals
        sftp.close()

    def close_ssh(ssh):
        try:
            ssh.close()
            print('SSH connection closed.')
        except:
            print("Something didn't work. Did you even have an ssh open?")
