package com.example.testdemo.config;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import jdk.nashorn.internal.scripts.JS;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.stereotype.Component;
import sun.rmi.runtime.Log;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description : 群发消息  //描述
 */
@Slf4j
@ServerEndpoint("/result")
@Component
public class SendObjectMessage {

    /** 记录当前在线连接数 */
    private static AtomicInteger onlineCount = new AtomicInteger(0);
    private static ConcurrentLinkedQueue<SendObjectMessage> socket = new ConcurrentLinkedQueue<SendObjectMessage>();
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    private SendObjectMessage mObject = null;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        socket.add(this);
        onlineCount.incrementAndGet(); // 在线数加1
        if(mObject == null){
            mObject = socket.peek();
        }
        /*try {
            sendMessage("连接成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        log.info("有新连接加入，当前在线人数为：{}", onlineCount.get());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        socket.remove(this);
        // 在线数减1
        onlineCount.decrementAndGet();
        log.info("用户退出，当前在线人数为：{}", onlineCount.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        if (message != null && !message.isEmpty()) {
            //socket.peek().sendMessage(message);
            JSONObject js = JSONObject.parseObject(message);
            String op = js.getString("op");

            if(op.equals("connect")){
                JSONObject content = js.getJSONObject("content");
                String user = content.getString("user");
                //JSONArray note = content.getJSONArray("note");
                Integer code = content.getInteger("code");
                Integer shelf = content.getInteger("shelf");
                Integer floor = content.getInteger("floor");

                System.out.println(content);
                mObject.sendMessage("confirm");

            }else if(op.equals("confirm")){
                String con = js.getString("content");
                if(con.equals("yes")){
                    try {
                        testSelenium1();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println("robot");
                }else if(con.equals("no")){
                    System.out.println("no");
                }
            }else if(op.equals("finish")){
                System.out.println("fin");
                mObject.onClose(mObject.session);
                socket.poll();

                if(socket.peek() != null){
                    mObject = socket.peek();
                    mObject.sendMessage("confirm");
                }else{
                    mObject = null;
                }
            }
        }
        log.info("服务端收到客户端的消息:{}", message);
    }

    @OnError
    public void onError(Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 服务端发送消息给客户端
     */
    public void sendMessage(String message) throws IOException {
        //如果开启@Async异步需要加锁，否则就会报错
        synchronized (session){
            this.session.getBasicRemote().sendText(message);
        }
    }

    /**
     * 自定义群发
     */

    public static void testSelenium1() throws Exception {
        // 使用HtmlUnitDriver 是不需要 安装 浏览器 和 驱动支持\
        System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setHeadless(true);

        WebDriver driver = new ChromeDriver(chromeOptions);
        //ChromeDriver driver = new ChromeDriver();

        JavascriptExecutor executor = (JavascriptExecutor) driver;
        String strFile = Thread.currentThread().getClass().getResource("/").getPath();
        //driver.get(strFile + "/test.html");
        driver.get("file://" + strFile + "/test.html");


    }
    private static String readJsFile(String url) throws Exception {
        StringBuffer script = new StringBuffer();

        File file = new File(url);
        FileReader filereader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(filereader);
        String tempString = null;
        while ((tempString = bufferedReader.readLine()) != null) {
            script.append(tempString).append("\n");
        }
        bufferedReader.close();
        filereader.close();
        return script.toString();
    }

}
