package com.fr.tx.main;

import java.awt.BorderLayout;
import java.awt.Robot;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.apache.log4j.Logger;
import org.jdesktop.application.SingleFrameApplication;

import com.fr.tx.common.data.CacheData;
import com.fr.tx.common.netty.eqt.TcpSendUtil;
import com.fr.tx.common.netty.eqt.TcpServer;
import com.fr.tx.common.netty.wbs.WebSocketServer;

import io.netty.channel.ChannelFuture;
/**
   * 通信端主函数
 */
public class SmartmonitorNetty extends SingleFrameApplication {
    /**
     * 日志
     */
    public static final Logger logger = Logger.getLogger(SmartmonitorNetty.class.getSimpleName());
    
    private JPanel topPanel;
    private static JTextArea flashuser;
    private static JScrollPane scrollPane;
    ChannelFuture f;
    @Override
    protected void startup() {
        {
            getMainFrame().setSize(600, 900);
            ImageIcon icon=new ImageIcon("iconImage");
            getMainFrame().setIconImage(icon.getImage());
        }
        topPanel = new JPanel();
        topPanel.setPreferredSize(new java.awt.Dimension(600, 500));
        topPanel.setLayout(null);
        topPanel.setName("topPanel");
        {
            flashuser = new JTextArea();
            flashuser.setBounds(0, 0, 600, 500);
            flashuser.setName("flashuser");
            flashuser.setLineWrap(true);
            flashuser.setAutoscrolls(true);
            scrollPane = new JScrollPane(flashuser);
            scrollPane.setBounds(0, 0, 600, 500);
            topPanel.add(scrollPane, BorderLayout.CENTER);
            getMainFrame().add(topPanel);
        }
        show(topPanel);
        doInitExit();
    }
    // 在应用程序的main方法里调用此函数保证程序只有一个实例在运行.
    @SuppressWarnings("resource")
    public static boolean makeSingle(String singleId) {
        RandomAccessFile raf = null;
        FileChannel channel = null;
        FileLock lock = null;
 
        try {
            // 在临时文件夹创建一个临时文件，锁住这个文件用来保证应用程序只有一个实例被创建.
            File sf = new File(System.getProperty("java.io.tmpdir") + singleId + ".single");
            sf.deleteOnExit();
            sf.createNewFile();

            raf = new RandomAccessFile(sf, "rw");
            channel = raf.getChannel();
            lock = channel.tryLock();
            if (lock == null) {
                // 如果没有得到锁，则程序退出.
                // 没有必要手动释放锁和关闭流，当程序退出时，他们会被关闭的.
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    
    //主方法
    public static void main(String[] args) throws Exception {
        if (makeSingle("SmartmonitorNetty")) {
            JOptionPane.showMessageDialog(null, "监测系统已经启动！");
            System.exit(0);
            return;
        }
        // 加载主画面
        launch(SmartmonitorNetty.class, args);
        Robot  r   =   new   Robot(); 
        r.delay(5000);
        // 发起http请求接受返回值等例子
//        HTTPRequest request = new HTTPRequest(new URL("http://localhost/smartmonitor/index.php/Station/search"));
//        String[] webpage = request.read();
//        JSONObject json = JSONObject.fromObject(webpage[0]);
//        System.out.println(json.getString("count"));
//        System.out.println(json.getString("data"));
//        JSONArray jsonArray = JSONArray.fromObject(json.getString("data"));
//        for(int i = 0 ;i < jsonArray.size() ; i++){
//            System.out.println("name = "+jsonArray.getJSONObject(i).getString("station_name"));
//        }
        
        // 注册站点通道
        CacheData.sessionBds.add("11");// 常州站
        CacheData.sessionBds.add("12");// 云亭站
        CacheData.sessionBds.add("13");// 长山站
        
//        new Thread(new Runnable() {
//            public void run() {
//                WebSocketServer ws = new WebSocketServer(flashuser,"7005","127.0.0.1");
//                ws.run();
//            }
//        }).start();
        
       for(int i = 0;i<=8;i++){
        	new Thread(new Runnable() {
                public void run() {
                	TcpSendUtil send1 = new TcpSendUtil("11",16);
                    send1.start();
                }
            }).start();
        }
        
       for(int i = 0;i<=8;i++){
        	new Thread(new Runnable() {
                public void run() {
                	TcpSendUtil send1 = new TcpSendUtil("12",28);
                    send1.start();
                }
            }).start();
        }

       /*         for(int i = 0;i<=8;i++){
        	new Thread(new Runnable() {
                public void run() {
                	TcpSendUtil send1 = new TcpSendUtil("13",14);
                    send1.start();
                }
            }).start();
        }*/

        // 启动Netty服务端口
        new TcpServer(flashuser).start();
    }
    
    // 增加程序关闭密码防止误操作
    private void doInitExit() {
        ExitListener maybeExit = new ExitListener() {
            @Override
            public boolean canExit(java.util.EventObject event) {
                String str = JOptionPane.showInputDialog("请输入四位数关闭密码");
                if(str==null){
                    return false;
                }else{
                    if ("6540".equals(str)) {
                        return true;
                    }else {
                        JOptionPane.showMessageDialog(null, "密码错误！");
                        return false;
                    }
                }
            }
            @Override
            public void willExit(java.util.EventObject event) {
                
            }
        };
        addExitListener(maybeExit);
    }
}
