text: /**
   * Copyright 2018 Google Inc. All Rights Reserved.
   *
   * 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 functions = require('firebase-functions');
  const {smarthome} = require('actions-on-google');
  const util = require('util');
  const admin = require('firebase-admin');
  // Initialize Firebase
  admin.initializeApp();
  const firebaseRef = admin.database().ref('/');
  
  exports.fakeauth = functions.https.onRequest((request, response) => {
    const responseurl = util.format('%s?code=%s&state=%s',
      decodeURIComponent(request.query.redirect_uri), 'xxxxxx',
      request.query.state);
    console.log(responseurl);
    return response.redirect(responseurl);
  });
  
  exports.faketoken = functions.https.onRequest((request, response) => {
    const grantType = request.query.grant_type
      ? request.query.grant_type : request.body.grant_type;
    const secondsInDay = 86400; // 60 * 60 * 24
    const HTTP_STATUS_OK = 200;
    console.log(`Grant type ${grantType}`);
  
    let obj;
    if (grantType === 'authorization_code') {
      obj = {
        token_type: 'bearer',
        access_token: '123access',
        refresh_token: '123refresh',
        expires_in: secondsInDay,
      };
    } else if (grantType === 'refresh_token') {
      obj = {
        token_type: 'bearer',
        access_token: '123access',
        expires_in: secondsInDay,
      };
    }
    response.status(HTTP_STATUS_OK)
      .json(obj);
  });
  
  const app = smarthome({
    debug: true,
    key: '<api-key>',
  });
  
  app.onSync((body) => {
    // TODO: Implement full SYNC response
    return {
      requestId: body.requestId,
      payload: {
        agentUserId: '123',
        devices: [{
          id: 'washer',
          type: 'action.devices.types.WASHER',
          traits: [
            'action.devices.traits.OnOff',
          ],
          name: {
            defaultNames: ['My Washer'],
            name: 'Washer',
            nicknames: ['Washer'],
          },
          deviceInfo: {
            manufacturer: 'Acme Co',
            model: 'acme-washer',
            hwVersion: '1.0',
            swVersion: '1.0.1',
          },
        }],
      },
    };
  });
  
  const queryFirebase = async (deviceId) => {
    const snapshot = await firebaseRef.child(deviceId).once('value');
    const snapshotVal = snapshot.val();
    return {
      on: snapshotVal.OnOff.on,
      isPaused: snapshotVal.StartStop.isPaused,
      isRunning: snapshotVal.StartStop.isRunning,
    };
  }
  
  // eslint-disable-next-line
  const queryDevice = async (deviceId) => {
    const data = await queryFirebase(deviceId);
    return {
      on: data.on,
      isPaused: data.isPaused,
      isRunning: data.isRunning,
    }
  }
  
  app.onQuery((body) => {
    // TODO: Implement QUERY response
    return {};
  });
  
  app.onExecute((body) => {
    // TODO: Implement EXECUTE response
    return {};
  });
  
  exports.smarthome = functions.https.onRequest(app);
  
  exports.requestsync = functions.https.onRequest(async (request, response) => {
    console.info('Request SYNC for user 123');
    try {
      const res = await app.requestSync('123');
      console.log('Request sync completed');
      response.json(res.data);
    } catch (err) {
      console.error(err);
      response.status(500).send(`Error requesting sync: ${err}`)
    }
  });
  
  /**
   * Send a REPORT STATE call to the homegraph when data for any device id
   * has been changed.
   */
  exports.reportstate = functions.database.ref('{deviceId}').onWrite((change, context) => {
    console.info('Firebase write event triggered this cloud function');
  });
  