package com.wdkl.ncs.android.middleware.udp;

import android.os.Environment;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wdkl.ncs.android.middleware.model.JsonResponse;
import com.wdkl.ncs.android.middleware.model.ThirdServerInfo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ServerInfoUtil {
    private final static String TAG = ServerInfoUtil.class.getSimpleName();

    private final static String WdklCloudServerAPIUrl = "http://api.base.wdklian.com/ncs_sync/server_info/";
    /**
     * 获取服务器IP及相关。注意：放在子线程调用，会阻塞主线程
     * @param id，设备识别码，IMEI、MAC或其它
     *
     * 优先从文件获取服务器信息
     * 文件示例：
    {
        "success":true,
        "data":{
            "third_server":"192.168.1.188",
            "third_server_port":8006
        }
    }

     第二段请求 /ncs_url/server_info
     返回示例：{"tcp_local_ip":"192.168.1.188","tcp_public_ip":"192.168.1.188","tcp_port":5080,"tcp_idle_seconds":60,"http_local_ip":"192.168.1.188","http_public_ip":"192.168.1.188","http_port":8006,"rtc_local_ip":"192.168.1.188","rtc_public_ip":"192.168.1.188","rtc_port":8188,"stun_server":"stun:8.129.220.143:3478","turn_server":["turn:8.129.220.143:3478?transport=tcp|wdklrtc|Wdkl2021Rtc","turn:8.129.220.143:3478?transport=udp|wdklrtc|Wdkl2021Rtc"],"server_time":1640767161}
     */
    public static ThirdServerInfo get(String id){
        //--------------------优先从文件获取
        JsonResponse jsonResponse = getFromStorageFile();
        if (jsonResponse != null && jsonResponse.success){
            JSONObject jsonObject = JSON.parseObject(jsonResponse.data.toString());
            ThirdServerInfo thirdServerInfo = new ThirdServerInfo(jsonObject.getString("third_server"), jsonObject.getInteger("third_server_port"));
            return thirdServerInfo;
        }

        //--------------------HTTP请求全局服务器获取
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(15 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(15 * 1000, TimeUnit.MILLISECONDS)
                .writeTimeout(15 * 1000, TimeUnit.MILLISECONDS)
                .build();
        Request request = new Request.Builder().url(WdklCloudServerAPIUrl + id)
                .get().build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if (response != null && response.isSuccessful()){
                jsonResponse = JSON.parseObject(response.body().string(), JsonResponse.class);
                if (jsonResponse.success){
                    JSONObject jsonObject = JSON.parseObject(jsonResponse.data.toString());
                    ThirdServerInfo thirdServerInfo = new ThirdServerInfo(jsonObject.getString("third_server"), jsonObject.getInteger("third_server_port"));
                    return thirdServerInfo;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //--------------------HTTP未请求成功，发送UDP获取
        String udpResponse = UdpClient.getInstance().broadMsg(UdpClient.SEARCH_SERVER,UdpClient.UDP_TARGET_PORT);
        jsonResponse = JSON.parseObject(udpResponse, JsonResponse.class);
        if (jsonResponse != null && jsonResponse.success){
            JSONObject jsonObject = JSON.parseObject(jsonResponse.data.toString());
            ThirdServerInfo thirdServerInfo = new ThirdServerInfo(jsonObject.getString("third_server"), jsonObject.getInteger("third_server_port"));
            return thirdServerInfo;
        }
        return null;
    }

    private static JsonResponse getFromStorageFile(){
        String encoding = "UTF-8";
        File file = new File(Environment.getExternalStorageDirectory() + "/server_info.json");
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        }
        try {
            String content = new String(filecontent, encoding);
            Log.i(TAG,content);
            JsonResponse response = JSON.parseObject(content, JsonResponse.class);
            return response;
        } catch (UnsupportedEncodingException e) {
            return JsonResponse.errorResponse(e.getMessage());
        } catch (Exception e){
            return JsonResponse.errorResponse(e.getMessage());
        }
    }
}
