/**
 * Created by tom on 2018/1/21.
 */
'use strict';
const Fs = require('fs');
const Https = require('https');
const WebSocket = require('ws');
const uuid = require('uuid');

var http = require("http");
var express = require("express");
var request = require("request");
const path = require('path');
var cmd = require('node-cmd');
var WXBizDataCrypt = require('./WXBizDataCrypt');

const BERRY_PI = 'BERRY_PI';
const LOGIN = 'Login';
const FORMID = 'SendFormId';
const ENCRYPT = 'EncryptedData';
const wsclients = {};
const wssclients = {};
const WebSocketServer = WebSocket.Server;
const ws = new WebSocketServer({
    port: 8089
});

var curcnt=1;
const appId = 'wx4680f6d1dc629d22';
const appSecret = 'cc6a16ee5545e887c94d238dfefefac0';
var formid;
var encryptedData;
var iv;

console.log("websocketServer Listen port : 8089");



ws.on('connection', function (ws) {
    console.log(`[WS SERVER] connection()`);
    ws.clientId = uuid.v1();
    wsclients[ws.clientId] = ws;
    console.log('client connected:'+ws.clientId);

    ws.on('message', function (message) {
        console.log(`[WS SERVER] Received: ${message}`);
        ws.send(`ECHO: ${message}`, (err) => {
            if (err) {
                console.log(`[WS SERVER] error: ${err}`);
            }
        });
    });
    ws.on('close', () => {
        console.log(`[WS SERVER] close`);
		if(ws.clientId) {
			delete wsclients[ws.clientId];
			console.log('wsclient:'+ws.clientId);
		}
    });
});


const httpsServer = Https.createServer({
    //key: Fs.readFileSync("/home/tom/node.js/websocket_ex1/private.key"),
    //cert: Fs.readFileSync("/home/tom/node.js/websocket_ex1/certificate.crt")
    key: Fs.readFileSync("./iot.twgigatech.cn.key"),
    cert: Fs.readFileSync("./iot.twgigatech.cn.crt")
});

const wss = new WebSocketServer({
    server: httpsServer
});

httpsServer.on('request', (req, res) => {
    res.writeHead(200);
    res.end('hello HTTPS world\n');
});

wss.on('connection', (ws) => {
    console.log(`[WSS SERVER] connection()`);
    ws.clientId = uuid.v1();
    wssclients[ws.clientId] = ws;
    console.log('client connected:'+ws.clientId);

    ws.on('message', function (message) {
        console.log(`[WSS SERVER] Received: ${message}`);
        /*
        ws.send(`ECHO: ${message}`, (err) => {
            if (err) {
                console.log(`[WSS SERVER] error: ${err}`);
            }
        });
        */
        try{
            const data = JSON.parse(message)
            switch(data.cmd){
                case BERRY_PI:
                    //client.publish('CAMERA/PHOTO', ws.clientId)
                    wssclients[ws.clientId].send(JSON.stringify({
                        cmd:"CAMERA/PHOTO",
                        //path: "http://iot.gigatech.tw:8000/pic/01.jpg"
                        path: "http://iot.twgigatech.cn:8090/image/0"+curcnt+".jpg"
                    }));
                    if (curcnt==1) {
                        curcnt++;
                        cmd.run('avconv -y -i rtsp://203.73.93.26:554/video1 -an -vframes 1 //home/tom/node.js/websocket_ex1/public/image/06.jpg');
                        console.log(`Get picture!!!!`);
                    }
                    else if (curcnt==6) curcnt=1;
                    else curcnt++;
                    return;
                case LOGIN:
					request.get({
						uri: 'https://api.weixin.qq.com/sns/jscode2session',
						json: true,
						qs: {
							grant_type: 'authorization_code',
							appid: appId,
							secret: appSecret,
							js_code: data.code
						}
					}, (err, response, data) => {
						if (response.statusCode === 200) {
							//TODO: 生成一个唯一字符串sessionid作为键，将openid和session_key作为值，存入redis，超时时间设置为2小时
							let secretValue = {
								openid: data.openid,
                                session_key: data.session_key,
                                unionid: data.unionid
							}
							console.log("OPEDID:"+data.openid+" ,SessionKey:"+data.session_key+" ,unionid:"+data.unionid);
						}
                    })
                    return;
                case FORMID:
                    formid = data.formId; 
					request.get({
						uri: 'https://api.weixin.qq.com/cgi-bin/token',
						json: true,
						qs: {
							grant_type: 'client_credential',
							appid: appId,
							secret: appSecret
						}
					}, (err, response, data) => {
						if (response.statusCode === 200) {
							//TODO: 生成一个唯一字符串sessionid作为键，将openid和session_key作为值，存入redis，超时时间设置为2小时
							let secretValue = {
								token: data.access_token,
								expires: data.expires_in
							}
                            console.log("TOKEN:"+data.access_token+" ,EXPIRES:"+data.expires_in+" FormID:"+formid);
                            
                            /*
                            var options = {
                                uri: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='+data.access_token,
                                method: 'POST',
                                body: {
                                    touser: 'oWxou5YnNOYAGrY676WQ057_DkWE',
                                    template_id: 'XiCgsxm-DH73hmAF0CJdlw4MORSDDcUXepF8vxRQz8A',
                                    //page: '点击模版卡片的跳转页面',
                                    form_id: formid,
                                    data: {
                                        keyword1:{
                                            value: '小程序测试模版',
                                            color: '#173177'
                                        },
                                        keyword2:{
                                            value: '2017年3月24日',
                                            color: '#173177'
                                        },
                                        keyword3:{
                                            value: 'iHleath',
                                            color: '#173177'
                                        }
                                    },
                                    //需要放大的关键字
                                    //emphasis_keyword: 'keyword1.DATA'
                                }
                              };

                              request (options, function (error, response, body) {
                                if (!error && response.statusCode == 200) {
                                  console.log(body.id) // Print the shortened url.
                                }
                              });
                              */
                              // Set the headers

                            // Configure the request
                            var nowDate = new Date();
                            var result = nowDate.toLocaleDateString() + " "+ nowDate.toLocaleTimeString();
                            var options = {
                                uri: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='+data.access_token,
                                method: 'POST',
                                json: true,
                                body: {
                                    touser: 'oWxou5YnNOYAGrY676WQ057_DkWE',
                                    //touser: 'oWxou5WRP3pWQOhAz9I9YAjVgo5Q',
                                    template_id: 'XiCgsxm-DH73hmAF0CJdlw4MORSDDcUXepF8vxRQz8A',
                                    //page: '点击模版卡片的跳转页面',
                                    form_id: formid,
                                    data: {
                                        keyword1:{
                                            value: '小程序测试模版',
                                            color: '#173177'
                                        },
                                        keyword2:{
                                            //value: '2018年3月6日9時53分',
                                            value: result,
                                            color: '#173177'
                                        },
                                        keyword3:{
                                            value: 'Gigatech小區',
                                            color: '#173177'
                                        }
                                    },
                                    //需要放大的关键字
                                    emphasis_keyword: 'keyword1.DATA'
                                }
                            }

                            // Start the request
                            request(options, function (error, response, body) {
                                if (!error && response.statusCode == 200) {
                                    // Print out the response body
                                    console.log(body)
                                }
                            })
						}
					})
					return;
					
				case ENCRYPT:
					encryptedData = data.encryptedData;
					iv = data.iv;
					request.get({
						uri: 'https://api.weixin.qq.com/sns/jscode2session',
						json: true,
						qs: {
							grant_type: 'authorization_code',
							appid: appId,
							secret: appSecret,
							js_code: data.code
						}
					}, (err, response, data) => {
						if (response.statusCode === 200) {
							//TODO: 生成一个唯一字符串sessionid作为键，将openid和session_key作为值，存入redis，超时时间设置为2小时
							let secretValue = {
								openid: data.openid,
                                session_key: data.session_key,
							}
							console.log("OPEDID:"+data.openid+" ,SessionKey:"+data.session_key);
							var pc = new WXBizDataCrypt(appId, data.session_key);
							var decode_data = pc.decryptData(encryptedData , iv);
							console.log("Name:"+decode_data.nickName+", unionId:"+ decode_data.unionId);
							console.log(decode_data);
						}
                    })
					return;
					
                default:
                    return;
            }
        }catch(e){
            console.log(e)
        }

    });
    ws.on('close', () => {
        console.log(`[WSS SERVER] close`);
		if(ws.clientId) {
			delete wssclients[ws.clientId];
			console.log('wssclient:'+ws.clientId);
		}
    });
});
httpsServer.listen(443);
console.log("secure websocketServer Listen port : 443");

var app = express();
app.use(express.static(path.join(__dirname, 'public')));

app.listen(8090, () => {
    console.log(`App listening at port 8090`)
})
