'use strict';

const http = require('http');
const Bot = require('messenger-bot');
let db_query = require('./db');

let bot = new Bot({
    token: process.env.PAGE_TOKEN
});

bot.on('error', (err) => {
    console.log(err.message)
});

bot.on('message', (payload, reply) => {
    let text = payload.message.text;
    let user_id = payload.sender.id;
    try {
        if (text.indexOf("등록") >= 0) {
            db_query(1, user_id, function cb(err, exists) {
                if (err) reply({text: "오류가 발생했습니다. 다시 시도해 주시겠어요?"}, (err) => {
                    if (err) console.log(err);
                });
                else if (exists) reply({text: "이미 등록하셨습니다."}, (err) => {
                    if (err) console.log(err);
                });
                else{
                    let https = require('https');
                    https.request({
                        host: 'graph.facebook.com',
                        path: `/v2.6/${payload.sender.id}?fields=first_name&access_token=${process.env.PAGE_TOKEN}`,
                        method: 'GET',
                        headers: {
                            'Content-Type': "application/json"
                        }
                    }, (res)=>{
                        res.setEncoding('utf8');
                        let result = '';
                        res.on('data', function (chunk) {
                            result += chunk;
                        });
                        res.on('end', ()=>{
                            let additional_greeting = '';
                            if(result.first_name) additional_greeting = `안녕하세요, ${result.first_name}님! `;
                            reply({text: additional_greeting+"등록해주셔서 감사합니다. 앞으로 급식/간식 정보를 보내드릴게요!"}, (err) => {
                                if (err) console.log(err)
                        });
                        })
                    });
                    let additional_greeting = '';
                    if(name) additional_greeting = `안녕하세요, ${name}님! `;
                    reply({text: additional_greeting+"등록해주셔서 감사합니다. 앞으로 급식/간식 정보를 보내드릴게요!"}, (err) => {
                        if (err) console.log(err)
                    });
                }
            });
        } else if (text.indexOf("해지") >= 0) {
            db_query(-1, user_id, function cb(err, exists) {
                if (err) reply({text: "오류가 발생했습니다. 다시 시도해 주시겠어요?"}, (err) => {
                    if (err) console.log(err);
                });
                else if (exists) reply({text: "해지되었습니다. 그동안 이용해 주셔서 감사합니다."}, (err) => {
                    if (err) console.log(err);
                });
                else reply({text: "음...등록하시지 않으셨는데요?"}, (err) => {
                        if (err) console.log(err)
                    });
            });

        }
    }catch (exception){
        reply({text: "꾸?"}, (err) => {
            if (err) console.log(err);
        });
    }
});

http.createServer(bot.middleware()).listen(process.env.PORT || 8080);
console.log('KSA meal bot subscription server running');
@@ -829,16 +829,65 @@
         
+ let data = '';%0A                    let request =
  https.r
@@ -891,24 +891,28 @@
 s.request(%7B%0A
+    
             
@@ -951,16 +951,20 @@
 k.com',%0A
+    
         
@@ -1096,16 +1096,20 @@
         
+    
 method: 
@@ -1139,16 +1139,20 @@
         
+    
 headers:
@@ -1154,16 +1154,20 @@
 ders: %7B%0A
+    
         
@@ -1237,34 +1237,42 @@
                 
-%7D%0A
+    %7D%0A    
                 
@@ -1283,24 +1283,28 @@
 %7D, (res)=%3E%7B%0A
+    
             
@@ -1348,45 +1348,8 @@
     
-                    let result = '';%0A
     
@@ -1430,22 +1430,24 @@
         
-result
+    data
  += chun
@@ -1465,36 +1465,44 @@
                 
-%7D);%0A
+    %7D);%0A    
                 
@@ -1549,32 +1549,36 @@
                 
+    
 let additional_g
@@ -1623,17 +1623,19 @@
     
-if(result
+    if(data
 .fir
@@ -1679,14 +1679,12 @@
 , $%7B
-result
+data
 .fir
@@ -1689,32 +1689,36 @@
 irst_name%7D%EB%8B%98! %60;%0A
+    
                 
@@ -1837,32 +1837,36 @@
                 
+    
 if (err) console
@@ -1866,33 +1866,35 @@
 console.log(err)
-%0A
+;%0A 
                 
@@ -1893,32 +1893,35 @@
                 
+   
 %7D);%0A            
@@ -1934,16 +1934,17 @@
       %7D)
+;
 %0A       
@@ -1984,110 +1984,83 @@
     
-let additional_greeting = '';%0A                    if(name) additional_greeting = %60%EC%95%88%EB%85%95%ED%95%98%EC%84%B8%EC%9A%94, $%7Bname%7D%EB%8B%98! %60;%0A
+request.on('error', (err)=%3E%7B%0A                        console.log(err);%0A    
     
@@ -2088,36 +2088,16 @@
 (%7Btext: 
-additional_greeting+
 %22%EB%93%B1%EB%A1%9D%ED%95%B4%EC%A3%BC%EC%85%94%EC%84%9C 
@@ -2155,32 +2155,36 @@
                 
+    
 if (err) console
@@ -2184,33 +2184,35 @@
 console.log(err)
-%0A
+;%0A 
                 
@@ -2207,33 +2207,95 @@
                 
-%7D
+   %7D);%0A                    %7D);%0A                    request.end(
 );%0A             

Handle error on requesting user first name