package com.example.chatapp.network;

import com.example.chatapp.ChatApplication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class SocketClient {
    private int id;
    private Socket socket;

    public int Connection(String address, int port) {
        try {
            this.socket = new Socket(address, port);
        } catch (IOException e) {
            return 1;
        }
        return 0;
    }

    public void Disconnect() {
        try {
            this.socket.close();
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
    }

    public boolean isDisconnected() {
        return (this.socket == null);
    }

    public boolean ping() {
        try {
            WriteLine("ping");
            if (Objects.equals(ReadLine(), "pong")) {
                return true;
            }
            return false;
        } catch (IOException e) {
            return false;
        }
    }

    public void WriteLine(String line) throws IOException {
        if (this.socket == null) {
            String address = ChatApplication.Companion.getAddress();
            int port = ChatApplication.Companion.getPort();
            try {
                this.socket = new Socket(address, port);
            } catch (IOException e) {
                throw new IOException("Non connecté, veuillez redémarrer l'application");
            }
        }

        OutputStream outputStream;
        try {
            outputStream = this.socket.getOutputStream();
        } catch (IOException e) {
            throw new IOException("Impossible d'ouvrir le flux de sortie");
        }
        if (outputStream != null) {
            PrintStream out = new PrintStream(outputStream);
            out.println(line);
            return;
        }
        throw new IOException("Erreur réseau inconnue");

    }

    public String ReadLine() throws IOException {
        if (this.socket == null) {
            String address = ChatApplication.Companion.getAddress();
            int port = ChatApplication.Companion.getPort();
            try {
                this.socket = new Socket(address, port);
            } catch (IOException e) {
                throw new IOException("Non connecté, veuillez redémarrer l'application");
            }
        }

        InputStream inputStream;
        String line;
        try {
            inputStream = this.socket.getInputStream();
        } catch (IOException e) {
            throw new IOException("Impossible d'ouvrir le flux d'entrée");
        }
        if (inputStream != null) {
            InputStreamReader in = new InputStreamReader(inputStream);
            BufferedReader input = new BufferedReader(in);
            try {
                line = input.readLine();
            } catch (IOException e) {
                throw new IOException("Echec de la lecture");
            }
            return line;
        }
        throw new IOException("Erreur réseau inconnue");
    }

    public String Login(String user, String password) throws IOException {
        String line = String.format("login %s %s\n", user, password);
        ChatApplication.Companion.setName(user);
        ChatApplication.Companion.setPass(password);
        WriteLine(line);
        String response = ReadLine();
        if (!response.startsWith("error")) {
            this.id = Integer.parseInt(response);
        } else {
            this.id = 0;
        }
        ChatApplication.Companion.setidUser(this.id);
        return response;
    }

    public String Logout() throws IOException {
        WriteLine("logout");
        ChatApplication.Companion.setPass("");
        ChatApplication.Companion.setName("");
        this.id = 0;
        return ReadLine();
    }

    public void addGeneralMessage(String message) throws IOException {
        Login(ChatApplication.Companion.getName(), ChatApplication.Companion.getPass());
        String line = String.format("msg %s\n", message);
        WriteLine(line);
        ReadLine();
    }

    public void addPrivateMessage(String message, int receiver) throws IOException {
        Login(ChatApplication.Companion.getName(), ChatApplication.Companion.getPass());
        String line = String.format("msg-%d %s\n", receiver, message);
        WriteLine(line);
        ReadLine();
    }

    public List<String> GeneralMessage() throws IOException {
        Login(ChatApplication.Companion.getName(), ChatApplication.Companion.getPass());
        WriteLine("get\n");
        String answer = ReadLine();
        return Arrays.asList(answer.split("\t"));
    }

    public List<String> getPrivateMessage(int id) throws IOException {
        Login(ChatApplication.Companion.getName(), ChatApplication.Companion.getPass());
        WriteLine(String.format("get-%d\n", id));
        String answer = ReadLine();
        return Arrays.asList(answer.split("\t"));
    }
}
