package com.twilio.clicktocall;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class CallController {

    private TwilioLine twilioLine;

    @Autowired
    public CallController(TwilioLine twilioLine) {
        this.twilioLine = twilioLine;
    }

    @RequestMapping("index")
    public String index() {
        return "index";
    }

    @RequestMapping("call")
    public ResponseEntity<String> call(HttpServletRequest request) {
        String phoneNumber = request.getParameter("phone");

        if (phoneNumber == null || phoneNumber.isEmpty()) {
            return new ResponseEntity<>("The phone number field can't be empty", HttpStatus.BAD_REQUEST);
        } else {
            try {
                twilioLine.call(phoneNumber, buildResponseUrl(request));
            } catch (Exception e) {
                String errorMessage = "Problem while processing request: "+
                        e.getMessage();
                return new ResponseEntity<>(errorMessage, HttpStatus.INTERNAL_SERVER_ERROR);
            }

            return new ResponseEntity<>("Phone call incoming!", HttpStatus.ACCEPTED);
        }
    }

    private String buildResponseUrl(HttpServletRequest request) {
        return request.getRequestURL().toString().replace(request.getRequestURI(), "") + "/connect";
    }

}

@@ -977,13 +977,76 @@
     
-try %7B
+return tryToCallTwilioUsing(phoneNumber, buildResponseUrl(request));
 %0A   
@@ -1054,77 +1054,294 @@
     
+%7D%0A
     
+%7D%0A%0A
     
-twilioLine.call(phoneNumber, buildResponseUrl(request));%0A    
+private ResponseEntity%3CString%3E tryToCallTwilioUsing(String phoneNumber, String responseUrl) %7B%0A        ResponseEntity%3CString%3E response = new ResponseEntity%3C%3E(%22Phone call incoming!%22, HttpStatus.ACCEPTED);%0A%0A        try %7B%0A            twilioLine.call(phoneNumber, responseUrl);%0A
     
@@ -1364,28 +1364,24 @@
 eption e) %7B%0A
-    
             
@@ -1460,20 +1460,16 @@
         
-    
 e.getMes
@@ -1484,34 +1484,34 @@
             
-    return
+response =
  new Respons
@@ -1581,26 +1581,19 @@
     
-    %7D%0A%0A   
+%7D%0A%0A
         
  ret
@@ -1592,92 +1592,24 @@
     
- 
 return 
-new R
+r
 esponse
-Entity%3C%3E(%22Phone call incoming!%22, HttpStatus.ACCEPTED);%0A        %7D
+;
 %0A   

refactor call method to improve call method readability