// Copyright 2018, Google, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

const { DialogflowApp } = require('actions-on-google');
const functions = require('firebase-functions');
const shiritori = require('./shiritori');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const dict = k => {
  return admin.database()
      .ref('food').child(k)
      .once('value')
      .then(snap => snap.val());
};

function welcomeHandler (app) {
  app.data.used = ['しりとり'];
  app.ask('しりとり');
}

function gameHandler (app) {
  shiritori.loaded.then(() => {
    const input = app.getRawInput();
    shiritori.interact(dict, input, app.data.used, {
      lose () {
        app.tell('ざんねん。');
      },
      win (word, kana) {
        if (word) {
          app.tell(`${word} [${kana}]`);
        } else {
          app.tell('すごい！');
        }
      },
      next (word, kana) {
        app.data.used.unshift(input);
        app.data.used.unshift(kana);
        app.ask({
          speech: word,
          displayText: `${word} [${kana}]`
        });
      }
    });
  });
}

function defaultHandler (app) {
  app.tell('しりとりのゲーム');
}

const actionMap = new Map();
actionMap.set('input.welcome', welcomeHandler);
actionMap.set('input.unknown', gameHandler);
actionMap.set('default', defaultHandler);

exports.shiritori = functions.https.onRequest((request, response) => {
  const app = new DialogflowApp({request, response});
  console.log('Request headers: ' + JSON.stringify(request.headers));
  console.log('Request body: ' + JSON.stringify(request.body));
  app.handleRequest(actionMap);
});
exports.shiritori.actionMap = actionMap;

@@ -1010,45 +1010,23 @@
 app.
-data.used = %5B'%E3%81%97%E3%82%8A%E3%81%A8%E3%82%8A'%5D;%0A  app.ask('%E3%81%97%E3%82%8A%E3%81%A8%E3%82%8A
+ask('%E3%81%A9%E3%81%86%E3%81%9E%E3%80%81%E5%A7%8B%E3%82%81%E3%81%A6%E4%B8%8B%E3%81%95%E3%81%84
 ');%0A
@@ -1218,16 +1218,25 @@
 l('%E3%81%96%E3%82%93%E3%81%AD%E3%82%93%E3%80%82
+%E3%81%82%E3%81%AA%E3%81%9F%E3%81%AE%E8%B2%A0%E3%81%91%E3%81%A7%E3%81%99%E3%80%82
 ');%0A    
@@ -1367,16 +1367,25 @@
 ll('%E3%81%99%E3%81%94%E3%81%84%EF%BC%81
+%E3%81%82%E3%81%AA%E3%81%9F%E3%81%AE%E5%8B%9D%E3%81%A1%E3%81%A7%E3%81%99%E3%80%82
 ');%0A    
@@ -1971,16 +1971,55 @@
 onse%7D);%0A
+  app.data.used = app.data.used %7C%7C %5B%5D;%0A
   consol

refactor conversation