package com.example.patrice.mysql01;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import com.jcraft.jsch.*;

// https://github.com/kayuda91/Temperature/blob/read_temp/app/src/main/java/com/example/eugenekayuda/temperature/MainActivity.java

// http://www.jcraft.com/jsch/examples/Sftp.java.html

public class SSH01 extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ssh01_layout);

        try {
            //String result = executeRemoteCommand("pi", "sdfghj", "82.234.53.234", 22);

            // fail car pas en mode asynchrone
            //cmd();

            // OK
            //sshConnect t = new sshConnect();
            //t.execute();

            // pas asynchrone
            //sftp();

            sftp t = new sftp();
            t.execute();

            int a = 51;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String executeRemoteCommand(String username,
                                       String password,
                                       String hostname,
                                       int port) throws Exception {
        JSch jsch = new JSch();
        Session session = jsch.getSession(username, hostname, 22);
        session.setPassword(password);


        Properties prop = new Properties();
        prop.put("StrictHostKeyChecking", "no");
        session.setConfig(prop);

        session.connect();

        // SSH Channel
        ChannelExec channelssh = (ChannelExec) session.openChannel("exec");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        channelssh.setOutputStream(baos);

        // Execute command
        channelssh.setCommand("ls");
        channelssh.connect();
        channelssh.disconnect();

        return baos.toString();
    }

    public void cmd() {

        String host = "82.234.53.234";
        String user = "pi";
        String password = "sdfghj";
        String command1 = "ls -ltr";

        try {

            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            JSch jsch = new JSch();
            Session session = jsch.getSession(user, host, 22);
            session.setPassword(password);
            session.setConfig(config);
            session.connect();
            System.out.println("Connected");

            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command1);
            channel.setInputStream(null);
            ((ChannelExec) channel).setErrStream(System.err);

            InputStream in = channel.getInputStream();
            channel.connect();

            byte[] tmp = new byte[1024];

            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
                    System.out.print(new String(tmp, 0, i));
                }

                if (channel.isClosed()) {
                    System.out.println("exit-status: " + channel.getExitStatus());
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception ee) {
                }
            }
            channel.disconnect();
            session.disconnect();
            System.out.println("DONE");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public class sshConnect extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... data) {
            JSch jsch = new JSch();
            Session session = null;
            Properties props = new Properties();
            props.put("StrictHostKeyChecking", "no");

            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            config.put("compression.s2c", "zlib,none");
            config.put("compression.c2s", "zlib,none");

            try {
                session = jsch.getSession("pi", "82.234.53.234", 22);

                //session.setConfig(config);
                session.setConfig("StrictHostKeyChecking", "no");
                session.setPassword("sdfghj");

                session.connect();


                //String command="cd Desktop/ && python auto2.py";
                String command = "echo $PWD";

                ChannelExec channel = (ChannelExec) session.openChannel("exec");
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                channel.setOutputStream(baos);
                //channel.setOutputStream(Baos);
                //channel.setInputStream(Bais);
                //Run Command
                channel.setCommand(command);
                //channel.setInputStream(null);
                //channel.setErrStream(System.err);
                channel.connect();


                try {
                    Thread.sleep(3500);
                } catch (Exception ee) {
                }

                channel.disconnect();
                session.disconnect();

                String alpha = baos.toString();

            } catch (JSchException e1) {
                e1.printStackTrace();
                //Toast.makeText(getApplicationContext(), "blabla", Toast.LENGTH_SHORT).show();
            }

            return null;

        }

        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getApplicationContext(), "Executed", Toast.LENGTH_SHORT).show();

        }


    }



    public class sftp extends AsyncTask<String, Void, String>
    {
        @Override
        protected String doInBackground(String... data)
        {
            try
            {
                JSch ssh = new JSch();
                Session session = ssh.getSession("pi", "82.234.53.234", 22);
                // Remember that this is just for testing and we need a quick access, you can add an identity and known_hosts file to prevent
                // Man In the Middle attacks
                java.util.Properties config = new java.util.Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
                session.setPassword("sdfghj");

                session.connect();
                Channel channel = session.openChannel("sftp");
                channel.connect();

                ChannelSftp sftp = (ChannelSftp) channel;

                //sftp.cd(directory);
                // If you need to display the progress of the upload, read how to do it in the end of the article

                // use the put method , if you are using android remember to remove "file://" and use only the relative path
                //sftp.put("/storage/emulated/0/saved.jpg", "/var/www/save.jpg");

                //sftp.get("/var/www/dgfdssdfdstest_raspberry.jpg");


                try {
                    try (FileOutputStream out = new FileOutputStream("/storage/emulated/0/alpha.jpg"))
                    {
                        InputStream in = sftp.get("/var/www/dgfdssdfdstest_raspberry.jpg");

                            // read from in, write to out
                            byte[] buffer = new byte[1024];
                            int len;
                            while ((len = in.read(buffer)) != -1)
                            {
                                out.write(buffer, 0, len);
                            }

                    }
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }


                Boolean success = true;

                if (success)
                {
                    // The file has been uploaded succesfully
                }

                channel.disconnect();
                session.disconnect();
            }

            catch (JSchException e)
            {
                System.out.println(e.getMessage().toString());
                e.printStackTrace();
            }

            catch (SftpException e)
            {
                System.out.println(e.getMessage().toString());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result)
        {
            Toast.makeText(getApplicationContext(), "Executed", Toast.LENGTH_SHORT).show();

        }


    }

    public void xxxsftp() {
        try {
            JSch ssh = new JSch();
            Session session = ssh.getSession("pi", "82.234.53.234", 22);
            // Remember that this is just for testing and we need a quick access, you can add an identity and known_hosts file to prevent
            // Man In the Middle attacks
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.setPassword("rainbow");

            session.connect();
            Channel channel = session.openChannel("sftp");
            channel.connect();

            ChannelSftp sftp = (ChannelSftp) channel;

            //sftp.cd(directory);
            // If you need to display the progress of the upload, read how to do it in the end of the article

            // use the put method , if you are using android remember to remove "file://" and use only the relative path
            sftp.put("/storage/0/saved.jpg", "/var/www/save.jpg");

            Boolean success = true;

            if (success) {
                // The file has been uploaded succesfully
            }

            channel.disconnect();
            session.disconnect();
        } catch (JSchException e) {
            System.out.println(e.getMessage().toString());
            e.printStackTrace();
        } catch (SftpException e) {
            System.out.println(e.getMessage().toString());
            e.printStackTrace();


        }


    }

}