package top.octopusyan.manager;

import javafx.application.Platform;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import top.octopusyan.config.ProxyConfig;
import top.octopusyan.config.ProxyConfig.ProxyServer;
import top.octopusyan.config.ProxyConfig.ProxyType;
import top.octopusyan.http.EasyHttp;
import top.octopusyan.http.listener.OnHttpListener;
import top.octopusyan.http.model.ResponseClass;
import top.octopusyan.manager.http.Api;
import top.octopusyan.manager.http.request.ProxySetup;
import top.octopusyan.utils.AlertUtil;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author : octopus yan
 * @email : octopus_yan@foxmail.com
 * @description :  代理设置工具
 * @create : 2022-4-5 09:56
 */
public class ProxyManager {
    private static String csrf;


    private static final String Null = "无";
    private static final String isOpen = "启用";

    /**
     * 初始化隧道设置
     */
    public static ProxySetup initProxy(Integer maxsort) {
        ProxySetup setup = new ProxySetup();
        setup.setNode(3);// 上海服务器
        setup.setLocal_ip("127.0.0.1");
        setup.setLocal_port(80);
        setup.setProxy_name("默认连接");
        setup.setProxy_type(StringUtils.lowerCase(ProxyType.HTTP.name()));
        setup.setDomain(".frp.octopusyan.top");
        setup.setSort(1);
        if (maxsort != null) setup.setSort(maxsort + 1);
        setup.setUse_compression(true);
        setup.setUse_encryption(true);
        setup.setStatus(true);
        setup.setRuning(false);
        return setup;
    }

    /**
     * 删除隧道
     *
     * @param id 隧道ID
     */
    public static void delete(Integer id) {
        EasyHttp.builder()
                .api(Api.DeleteProxy())
                .pathParam(String.valueOf(id), csrf)
                .request(new OnHttpListener<String>() {
                    @Override
                    public void onSucceed(String result) {

                    }

                    @Override
                    public void onFail(Exception e) {

                    }
                });
    }

    /**
     * 获取隧道详情信息
     */
    public static ProxySetup info(ProxySetup setup) {

        String html;
        try {
            html = EasyHttp.builder()
                    .api(Api.ProxyInfo())
                    .pathParam(String.valueOf(setup.getId()))
                    .execute(new ResponseClass<String>() {
                    });
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        Document doc = Jsoup.parse(html);
        Elements select = doc.select("tbody > tr > td");

        String serverStr = select.get(0).text();
        String localIp = select.get(3).text();
        String localPort = select.get(4).text();
        String webPort = select.get(5).text();
        String useEnc = select.get(6).text();
        String useCom = select.get(7).text();
        String domain = select.get(8).text();
        String sk = select.get(11).text();
        String status = select.get(13).text();
        String httpUser = select.get(15).text();
        String httpPwd = select.get(16).text();
        String serverName = select.get(17).text();

        for (ProxyServer value : ProxyServer.values()) {
            String name = value.getServerName();
            if (serverStr.contains(name))
                setup.setNode(ProxyConfig.getServerNode(name));
        }
        setup.setLocal_ip(localIp);
        setup.setLocal_port(Integer.parseInt(localPort));
        setup.setRemote_port(Null.equals(webPort) ? "" : webPort);
        setup.setDomain(Null.equals(domain) ? "" : domain);
        setup.setUse_compression(useCom.equals(isOpen));
        setup.setUse_encryption(useEnc.equals(isOpen));
        setup.setStatus(status.equals(isOpen));
        setup.setSk(Null.equals(sk) ? null : sk);
        setup.setHttp_user(Null.equals(httpUser) ? null : httpUser);
        setup.setHttp_pwd(Null.equals(httpPwd) ? null : httpPwd);
        setup.setServer_name(Null.equals(serverName) ? null : serverName);

        return setup;
    }

    public static int randomPort() {
        try {
            return Integer.parseInt(EasyHttp.builder()
                    .api(Api.RandomPort())
                    .execute(new ResponseClass<String>() {
                    }));
        } catch (Exception e) {
            e.printStackTrace();
            return (int) (Math.random() * 1000 + 30000);
        }
    }

    /**
     * 获取用户隧道列表
     */
    public static void getList(OnHttpListener<List<ProxySetup>> listener) {
        EasyHttp.builder()
                .api(Api.ProxyList)
                .request(new OnHttpListener<String>() {
                    @Override
                    public void onSucceed(String result) {
                        Document doc = Jsoup.parse(result);
                        Elements elementsByClass = doc.select("table > tbody > tr");

                        List<ProxySetup> proxySetupList = elementsByClass.stream().map(element -> {
                            ProxySetup proxySetup = new ProxySetup();
                            Elements tds = element.getElementsByTag("td");
                            proxySetup.setId(Integer.parseInt(tds.get(0).text()));
                            proxySetup.setProxy_name(tds.get(1).text());
                            proxySetup.setProxy_type(tds.get(2).text());
                            proxySetup.setSort(Integer.parseInt(tds.get(5).text()));

                            ProxySetup info = info(proxySetup);
                            if (info != null) return info;
                            return proxySetup;
                        }).collect(Collectors.toList());

                        Platform.runLater(() -> listener.onSucceed(proxySetupList));
                    }

                    @Override
                    public void onFail(Exception e) {
                        AlertUtil.exception(e).show();
                    }
                });
    }

    public static void add(OnHttpListener<ProxySetup> listener, ProxySetup setup) {
        EasyHttp.builder()
                .api(Api.AddProxy())
                .param(setup)
                .request(new OnHttpListener<String>() {
                    @Override
                    public void onSucceed(String result) {

                        // 不成功
                        if (!result.contains("成功")) {
                            Platform.runLater(() -> AlertUtil.error(result).header(null).show());
                            listener.onSucceed(null);
                            return;
                        }

                        getList(new OnHttpListener<List<ProxySetup>>() {
                            @Override
                            public void onSucceed(List<ProxySetup> result) {

                                if (result != null && result.size() > 0) {
                                    for (ProxySetup proxySetup : result) {
                                        if (Objects.equals(proxySetup.getSort(), setup.getSort())) {
                                            listener.onSucceed(proxySetup);
                                            return;
                                        }
                                    }
                                    listener.onSucceed(null);
                                }
                                listener.onSucceed(null);
                            }

                            @Override
                            public void onFail(Exception e) {

                            }
                        });
                    }

                    @Override
                    public void onFail(Exception e) {

                    }
                });
    }

    public static String getCsrf() {
        return csrf;
    }

    public static void setCsrf(String htmlStr) {
        int i = htmlStr.indexOf("var csrf_token = \"");
        int i1 = htmlStr.indexOf("\"", i + 18);
        ProxyManager.csrf = htmlStr.substring(i + 18, i1);
    }
}
