package io.geekidea.springbootplus.test;

import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
public class FirebaseTest {

    public static void main(String[] args) {
        for (int i = 0; i < 1; i++) {
            extracted();
        }
    }

    private static void extracted() {
        //        System.set
        // SOCKS 代理，支持 HTTP 和 HTTPS 请求
        // 注意：如果设置了 SOCKS 代理就不要设 HTTP/HTTPS 代理
        System.setProperty("socksProxyHost", "127.0.0.1");
        System.setProperty("socksProxyPort", "7891");

//        String to = "ck_oO93kR42WlkmzBVjzcA:APA91bGTcXlFq9_AOvGOJSIB4Z38EOqhP3_6HQ18_XIn3othxSWTeRr_IaQn-75AB9FvD5CiTig03Y56VtZDEEihismai0OOMPyxB7R4ajaFrQszEQRbCBw3iUgaAyjK7e1RFeq22tRC";
        String to = "eLOQs869208Wq5_tQINUgl:APA91bEsiSt8_RBJYQ2bLDHJF4nuE6XS6bP-kdEAt463SpW2i0Q5wUcmma3ylszr698MUIkjkwV507EV7ao347pl0XwHTDgDM1kIL4WYfX28OznML2lefnYS7oMmlt5_uqvwDO1GWone";
        String key = "AAAA7PNYwIg:APA91bG2PZlTpC9sxqeIxtKDJJGzGZlh1ca13_bR4c5qkv9pEvRxcDfgO8VQqV2g-7cCTZz3oDtpWAgcQ5TyMKGdlD7Zp3bEmFkpNYDJAIcshSbyW-BtjCbknT2R5px5THmEJrlTJuDi";

        String jsonStr = null;
        try {
            URL url = new URL("https://fcm.googleapis.com/fcm/send");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setConnectTimeout(10000);
            conn.setRequestMethod("POST");
            //不设置默认发送文本格式。设置就是json
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Authorization", "key=" + key);
            JSONObject json = new JSONObject();
            //推送到哪台客户端机器
            json.put("to", to);
            JSONObject info = new JSONObject();
            info.put("title", "33新消息11");
            info.put("body", "点击查看");
            //数据消息data  通知消息 notification
            json.put("notification", info);

            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            jsonStr = json.toString();
            wr.write(jsonStr);
            wr.flush();
            InputStream inputStream = conn.getInputStream();
            InputStreamReader in = new InputStreamReader(inputStream);
            BufferedReader reader = new BufferedReader(in);
            String line = reader.readLine();

            log.debug(line);

            wr.close();
            reader.close();
        } catch (Exception e) {
            log.error("FCM push failure: " + jsonStr, e);
        }
    }
}

