/*
 * Copyright (c) 2011-2017 Nexmo Inc
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.nexmo.quickstart.voice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nexmo.client.voice.ncco.Ncco;
import com.nexmo.client.voice.ncco.RecordNcco;
import com.nexmo.client.voice.ncco.TalkNcco;
import spark.Request;
import spark.Route;

import java.io.IOException;

import static spark.Spark.*;

public class RecordCall {
    public static void main(String[] args) throws Exception {
        ObjectMapper nccoMapper = new ObjectMapper();

        /*
         * Route to answer incoming calls with an NCCO response.
         */
        Route answerRoute = (req, res) -> {
            String recordingUrl = String.format("%s://%s/webhooks/recording", req.scheme(), req.host());

            TalkNcco intro = new TalkNcco("Please leave a message after the tone, then press pound.");
            RecordNcco record = new RecordNcco();
            record.setEndOnKey('#');
            record.setBeepStart(true);
            record.setEventUrl(recordingUrl);
            TalkNcco thanks = new TalkNcco("Thank you for your message.");
            Ncco[] nccos = new Ncco[]{intro, record, thanks};
            res.type("application/json");
            return nccoMapper.writer().writeValueAsString(nccos);
        };

        /**
         * Webhook Route which prints out the recording URL it is given to stdout.
         */
        Route recordingWebhookRoute = (req, res) -> {
            System.out.printf("Recording URL = %s\n", extractRecordingUrl(req));

            res.status(204);
            return "";
        };

        port(3000);

        get("/webhooks/answer", answerRoute);
        post("/webhooks/answer", answerRoute);

        get("/webhooks/recording", recordingWebhookRoute);
        post("/webhooks/recording", recordingWebhookRoute);
    }

    /**
     * Extract the provided recording_url either from the request params, or JSON body.
     */
    private static String extractRecordingUrl(Request req) throws IOException {
        String recordingUrl = req.queryParams("recording_url");
        if ("GET".equals(req.requestMethod())) {
            return recordingUrl;
        } else {
            if (recordingUrl != null) {
                return recordingUrl;
            } else {
                RecordingPayload payload = RecordingPayload.fromJson(req.bodyAsBytes());
                return payload.getRecordingUrl();
            }
        }
    }
}

@@ -1236,16 +1236,23 @@
 ce.ncco.
+Connect
 Ncco;%0Aim
@@ -1284,22 +1284,16 @@
 ce.ncco.
-Record
 Ncco;%0Aim
@@ -1325,20 +1325,22 @@
 ce.ncco.
-Talk
+Record
 Ncco;%0Aim
@@ -1355,15 +1355,14 @@
 rk.R
-equest;
+oute;%0A
 %0Aimp
@@ -1370,47 +1370,41 @@
 rt s
-park.Route;%0A%0Aimport java.io.IOException
+tatic com.nexmo.quickstart.Util.*
 ;%0A%0Ai
@@ -1505,80 +1505,9 @@
 gs) 
-throws Exception %7B%0A        ObjectMapper nccoMapper = new ObjectMapper();
+%7B
 %0A%0A  
@@ -1542,16 +1542,28 @@
  answer 
+and connect 
 incoming
@@ -1578,24 +1578,17 @@
 ith 
-an NCCO response
+recording
 .%0A  
@@ -1751,111 +1751,8 @@
 );%0A%0A
-            TalkNcco intro = new TalkNcco(%22Please leave a message after the tone, then press pound.%22);%0A
     
@@ -1824,22 +1824,32 @@
 setE
-ndOnKey('#'
+ventUrl(recordingUrl
 );%0A
+%0A
     
@@ -1860,156 +1860,212 @@
     
-record.setBeepStart(true);%0A            record.setEventUrl(recordingUrl);%0A            TalkNcco thanks = new TalkNcco(%22Thank you for your message.%22
+String TO_NUMBER = envVar(%22TO_NUMBER%22);%0A            String NEXMO_NUMBER = envVar(%22NEXMO_NUMBER%22);%0A            ConnectNcco connect = new ConnectNcco(TO_NUMBER);%0A            connect.setFrom(NEXMO_NUMBER
 );%0A
+%0A
     
@@ -2102,23 +2102,16 @@
 o%5B%5D%7B
-intro, 
 record, 
 than
@@ -2110,17 +2110,19 @@
 rd, 
-thanks
+connect
 %7D;%0A
+%0A
     
@@ -2183,17 +2183,25 @@
 rn n
-cco
+ew Object
 Mapper
+()
 .wri
@@ -2251,25 +2251,24 @@
 %0A%0A        /*
-*
 %0A         * 
@@ -2437,11 +2437,11 @@
 rint
-f(%22
+ln(
 Reco
@@ -2449,28 +2449,46 @@
 ding
- URL = %25s%5Cn%22, extrac
+Payload.fromJson(req.bodyAsBytes()).ge
 tRec
@@ -2497,19 +2497,16 @@
 dingUrl(
-req
 ));%0A%0A   
@@ -2586,17 +2586,16 @@
 (3000);%0A
-%0A
         
@@ -2660,765 +2660,43 @@
 oks/
-answer%22, answerRoute);%0A%0A        get(%22/webhooks/recording%22, recordingWebhookRoute);%0A        post(%22/webhooks/recording%22, recordingWebhookRoute);%0A    %7D%0A%0A    /**%0A     * Extract the provided recording_url either from the request params, or JSON body.%0A     */%0A    private static String extractRecordingUrl(Request req) throws IOException %7B%0A        String recordingUrl = req.queryParams(%22recording_url%22);%0A        if (%22GET%22.equals(req.requestMethod())) %7B%0A            return recordingUrl;%0A        %7D else %7B%0A            if (recordingUrl != null) %7B%0A                return recordingUrl;%0A            %7D else %7B%0A                RecordingPayload payload = RecordingPayload.fromJson(req.bodyAsBytes());%0A                return payload.getRecordingUrl();%0A            %7D%0A        %7D
+recording%22, recordingWebhookRoute);
 %0A   

Clean up for building blocks.