package admin.server;

import admin.server.decryptlog.Decrupt;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class Server {
    static ParamServer ps = new ParamServer();
    static Decrupt decrupt = new Decrupt();

    private static DataOutputStream dataOutputStream = null;
    private static DataInputStream dataInputStream = null;


    public static void main(String[] args) {
        try {
            work();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void work() throws Exception {
        DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        Date date = new Date();
        String log_crupt = dateFormat.format(date) + "_crupr" + ".zip";
        receiveFile(log_crupt, ps.getPort());

        // работоа с раскриптовкой лога
        decrupt.decryptor(log_crupt, dateFormat.format(date) + "_decrupr" + ".zip", ps.getKey_decrupt_log());

        // удаляем криптованный zip архив
        Thread.sleep(2000);
        new File(log_crupt).delete();

        work();
    }

    // receive file function is start here
    private static void receiveFile(String fileName, int port) {
        try {
            SSLServerSocketFactory sslServerSocketFactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
            SSLServerSocket serverSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(port); // Порт для прослушивания входящих соединений

            System.out.println("Ждем подключения клиента...");
            SSLSocket clientSocket = (SSLSocket) serverSocket.accept(); // Принимаем входящее зашифрованное соединение

            System.out.println("Клиент подключен.");

            InputStream inputStream = clientSocket.getInputStream();
            ZipInputStream zipInputStream = new ZipInputStream(inputStream);

            ZipEntry entry;
            while ((entry = zipInputStream.getNextEntry()) != null) {
                fileName = entry.getName();
                FileOutputStream fileOutputStream = new FileOutputStream(fileName);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = zipInputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, length);
                }
                fileOutputStream.close();
                System.out.println("Файл " + fileName + " принят.");
            }

            zipInputStream.close();
            clientSocket.close();
            serverSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
    private static void receiveFile(String fileName, int port) {

        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Server started. Waiting for client connection...");
            Socket clientSocket = serverSocket.accept();
            System.out.println("Client connected.");

            InputStream inputStream = clientSocket.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);

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

            fileOutputStream.close();
            inputStream.close();
            clientSocket.close();
            System.out.println("File received successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
     */
}
