/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uk.ac.reload.dweezil;

//import com.suma.repository.RepositoryClient;
import com.uvigo.tMaestro.SCOCreator.tool.MainFrame;
import java.awt.*;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import org.apache.commons.net.ftp.FTPFile;
import uk.ac.reload.editor.EditorFrame;
import uk.ac.reload.editor.EditorInternalFrame;
import java.io.*;
import java.net.*;
import java.util.Vector;


import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
import org.apache.commons.net.ftp.FTPReply;
import uk.ac.reload.editor.contentpackaging.editor.resourceview.CP_ResourcesPanel;
import com.uvigo.tMaestro.SCOCreator.tool.ProgressBar;
import com.uvigo.tMaestro.SCOCreator.tool.Code;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;

/**
 *
 * @author Silvia
 */
public class Upload extends EditorInternalFrame {
//de momento no introducimos el valor de la ip, putada...

    boolean correcto = true;
    static FTPClient ftp;
    String server;
    String username;
    String password;
    static String remote;
    static String local;
    static String sDirectorio = "c:\\silviCourse";
    public Thread th;
    public static JFrame frame;

    public Upload() {


        try {

            int[] IP = null;
            String cadena = "Write de server IP and port\n (Format: XXX.XXX.XXX.XXX:XXXX)";
            //   JOptionPane pane = new JOptionPane(arguments);
            //de momento lo quito pq da igual lo de introducir la IP
            while (!correcto) {
                IP = new int[5];

                JOptionPane pane = new JOptionPane();
                //pane.set.Xxxx(...); // Configure
                String s = pane.showInputDialog(this, cadena, "Upload course to server", JOptionPane.PLAIN_MESSAGE);

                System.out.println(s);



                String sub;
                String aux = s;

                //ahora voy a comprobar el formato
                cadena = "BAD FORMAT\n Write de server IP and port\n (Format: XXX.XXX.XXX.XXX:XXXX)";
                if (s != null) {
                    boolean puerto = false;
                    for (int i = 0; i < 4; i++) {

                        int index = aux.indexOf(".");
                        if (index == -1) {

                            System.out.println("puerto");
                            index = aux.indexOf(":");
                            puerto = true;
                        }
                        if (((i == 3) & (!puerto)) || ((i != 3) && (puerto))) {
                            correcto = false;
                            break;
                        }
                        // System.out.println(index);
                        if (index == -1) {
                            correcto = false;
                            break;
                        } else {
                            sub = aux.substring(0, index);
                            aux = aux.substring(index + 1, aux.length());
                            // System.out.println(sub);
                            try {
                                int valor = Integer.parseInt(sub);
                                if ((!puerto) && (valor > 255)) {
                                    correcto = false;
                                    break;
                                } else if (!puerto) {
                                    IP[i] = valor;
                                } else if (puerto) {
                                    // System.out.println("entro aqui");
                                    IP[i] = valor;
                                    try {
                                        valor = Integer.parseInt(aux);
                                    } catch (Exception e) {
                                        correcto = false;
                                        e.printStackTrace();
                                        break;
                                    }
                                    IP[i + 1] = valor;
                                }
                            } catch (Exception e) {
                                correcto = false;
                                e.printStackTrace();
                                break;
                            }
                            correcto = true;
                        }
                    }
                } else {
                    IP = null;
                    correcto = true;
                }
            }



            if (IP != null) {

                for (int i = 0; i < IP.length; i++) {
                    System.out.println(IP[i]);
                }
            }
            JOptionPane pane = new JOptionPane();
            int n = pane.showConfirmDialog(this,
                    "Do you want to upload the course to the server?", "Upload course to server",
                    JOptionPane.YES_NO_OPTION);

            System.out.println(n);
            if (n == JOptionPane.YES_OPTION) {


                System.out.println("Invocamos el método registerCourseURL()");
                Vector<String> datos = new Vector<String>();
                //Vector<String> datos = RepositoryClient.getInstance().registerCourse();
                //String[] urls = RepositoryClient.getInstance().getCoursesURL();
                System.out.println("Resultado:");
                for (String dato : datos) {
                    System.out.println(" > " + dato);
                }

                boolean storeFile = true;
                boolean binaryTransfer = false;
                boolean error = false;




                server = datos.get(0);
                username = datos.get(2);
                password = datos.get(3);
                remote = datos.get(1);
                local = "C:/a.txt"; //obtenerlo de reloadTotal


                ftp = new FTPClient();
                //ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));


                try {
                    int reply;
                    ftp.connect(server);
                    System.out.println("Connected to " + server + ".");

                    // After connection attempt, you should check the reply code to verify
                    // success.
                    reply = ftp.getReplyCode();

                    if (!FTPReply.isPositiveCompletion(reply)) {
                        ftp.disconnect();
                        System.err.println("FTP server refused connection.");
                        System.exit(1);
                    }
                } catch (IOException e) {
                    if (ftp.isConnected()) {
                        try {
                            ftp.disconnect();
                        } catch (IOException f) {
                            // do nothing
                        }
                    }
                    System.err.println("Could not connect to server.");
                    e.printStackTrace();
                    System.exit(1);
                }

                __main:
                try {
                    if (!ftp.login(username, password)) {
                        ftp.logout();
                        error = true;
                        System.out.println("error de login");
                        break __main;
                    }

                    System.out.println("Remote system is " + ftp.getSystemName());

                    if (binaryTransfer) {
                        ftp.setFileType(FTP.BINARY_FILE_TYPE);

                    // Use passive mode as default because most of us are
                    // behind firewalls these days.
                    }
                    ftp.enterLocalPassiveMode();

                    if (storeFile) {

                        System.out.println("el directorio a copiar " + System.getProperties().getProperty("user.dir"));
                        ftp.changeWorkingDirectory(remote);

                        CP_ResourcesPanel _resourcepanel = CP_ResourcesPanel.getInstance();
                        File f = _resourcepanel._resource;
                        System.out.println(f.getAbsolutePath());
                        sDirectorio = f.getAbsolutePath();
                        File directorio = new File(sDirectorio);
                        copiarDirectorio(directorio);
                    //custom title, error icon

                    } else {
                        OutputStream output;

                        output = new FileOutputStream(local);

                        ftp.retrieveFile(remote, output);

                        output.close();
                    }

                    ftp.logout();
                } catch (FTPConnectionClosedException e) {
                    error = true;
                    System.err.println("Server closed connection.");
                    e.printStackTrace();
                } catch (IOException e) {
                    error = true;
                    e.printStackTrace();
                } finally {
                    if (ftp.isConnected()) {
                        try {
                            ftp.disconnect();
                        } catch (IOException f) {
                            // do nothing
                        }
                    }
                }

            } else {
                System.out.print("no subo nada");
            }
        } catch (Exception ex) {
            Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public boolean applicationClosing() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void copiarDirectorio(File f) {
        File[] ficheros = f.listFiles();

        for (int x = 0; x <
                ficheros.length; x++) {
            try {
                //System.out.println(separador + ficheros[x].getName());

                if (ficheros[x].isDirectory()) {
                    System.out.println("creo directorio " + ficheros[x].getName());
                    String ruta1 = ficheros[x].getPath();
                    String ruta2 = ficheros[x].getPath();
                    int lonraiz = f.getAbsolutePath().length();
                    int lonraiz2 = sDirectorio.length();
                    ruta1 =
                            ruta1.substring(lonraiz + 1, ruta1.length());
                    ruta2 =
                            ruta2.substring(lonraiz2, lonraiz);
                    ftp.changeWorkingDirectory("/" + remote + ruta2);
                    ftp.makeDirectory(ruta1);
                    ftp.changeWorkingDirectory(ruta1);
                    copiarDirectorio(ficheros[x]);
                } else {
                    System.out.println("almaceno fichero " + ficheros[x].getName());
                    InputStream input;
                    input =
                            new FileInputStream(ficheros[x].getAbsolutePath());
                    ftp.storeFile(ficheros[x].getName(), input);
                    input.close();
                }

            } catch (IOException ex) {
                int n = JOptionPane.showConfirmDialog(this,
                        "An error was ocurred, wrong upload\n try again?", "Error",
                        JOptionPane.YES_NO_OPTION);
                System.out.println(n);
                if (n == JOptionPane.YES_OPTION) {
                    System.out.println("volver a intentar");
                } else {
                    System.out.println("salir sin volver a intentarlo");
                }

                System.out.println("OJOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO");
                Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);

            }
        }
    }
}


