package com.example.testdemo.manager;

import com.alibaba.fastjson.JSONObject;
import com.example.testdemo.entity.Good;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;


@Slf4j
@ServerEndpoint("/result")
@Component
public class MessageManager {

    @Autowired
    private GoodManager gmanager;
    private static String TAG = "SendObjectMessage";
    private static AtomicInteger onlineCount = new AtomicInteger(0);
    private static ConcurrentLinkedQueue<MessageManager> socket = new ConcurrentLinkedQueue<MessageManager>();


    private Session session;
    private MessageManager mObject = null;

    @OnOpen
    public void onOpen(Session session) {

        log.info(TAG, "open");
        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) {

        log.info(TAG, "onclose");
        socket.remove(this);
        // 在线数减1
        onlineCount.decrementAndGet();
        log.info("用户退出，当前在线人数为：{}", onlineCount.get());
    }


    @OnMessage
    public void onMessage(String message, Session session) throws IOException {

        log.info(TAG, "onMessage");
        if (message != null && !message.isEmpty()) {

            log.info(TAG, "message has value");
            //socket.peek().sendMessage(message);
            JSONObject js = JSONObject.parseObject(message);
            String op = js.getString("op");

            if(op.equals("connect")){
                log.info(TAG, "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 {

                        log.info(TAG, "testSelenium");

                        testSelenium();

                    } catch (Exception e) {

                        e.printStackTrace();

                    }
                    System.out.println("robot");
                }else if(con.equals("no")){
                    System.out.println("no");
                }
            }else if(op.equals("finish")){
                log.info(TAG, "finish");
                mObject.onClose(mObject.session);
                socket.poll();

                if(socket.peek() != null){
                    log.info(TAG, "has no ths first node");
                    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异步需要加锁，否则就会报错

        log.info(TAG, "sendMessage");
        synchronized (session){
            this.session.getBasicRemote().sendText(message);
        }
    }


    public static void testSelenium() throws Exception {//打开浏览器调用js文件
        // 使用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 {//读取js文件

        log.info(TAG, "readjsfile");
        StringBuffer script = new StringBuffer();

        File file = new File(url);
        FileReader filereader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(filereader);//读取js文件
        String tempString = null;
        while ((tempString = bufferedReader.readLine()) != null) {
            script.append(tempString).append("\n");
        }
        bufferedReader.close();
        filereader.close();
        return script.toString();//返回读取的文件流
    }

    public void queryGoodsById(int id){
        List<Good> goodsList = gmanager.queryGoodsById(id);

        for(Good g:goodsList){
            System.out.println(g);
        }

    }

    public void  queryGoodsByPhonenum(String phonenum){
    List<Good> goodsList = gmanager.queryGoodsByPhonenum(phonenum);

        for(Good g:goodsList) {
            System.out.println(g);
        }
    }
}
