package hello;

import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.ui.Model;
import org.springframework.util.MimeTypeUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Controller
public class SendPushController {
    private static final String UTF_8 = "utf-8";
    private final Logger logger = LoggerFactory.getLogger(SendPushController.class);
    private Environment env;
    private String fcmKey;
    private String fcmSendUrl;

    public SendPushController(Environment env) {
        logger.debug("SendPush controller created.");
        this.env = env;
        this.fcmKey = this.env.getProperty("fcm.key");
        this.fcmSendUrl = this.env.getProperty("fcm.send.url");
    }

    @RequestMapping("/sendpush")
    // http://localhost:8181/sendpush
    public String sendpush(Model model) {
        logger.info("Greeting sendpush called.");
        model.addAttribute("title", "Send push");
        return "sendpush";
    }

    @RequestMapping(value = "/sendpushform", method = RequestMethod.POST)
    public String sendpushform(@RequestParam("dev_token") String devToken,
            @RequestParam("message_title") String messageTitle, @RequestParam("message") String message, Model model) {
        logger.info("Greeting sendpushform called.");
        model.addAttribute("devToken", devToken);
        model.addAttribute("message", message);
        model.addAttribute("messageTitle", messageTitle);
        model.addAttribute("title", "Send push result");

        try {
            URL url = new URL(this.fcmSendUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(HttpMethod.POST.name());

            connection.setRequestProperty(HttpHeaders.CONTENT_TYPE,
                    MimeTypeUtils.APPLICATION_JSON_VALUE + "; " + UTF_8);
            connection.setRequestProperty(HttpHeaders.ACCEPT, MimeTypeUtils.APPLICATION_JSON_VALUE);
            connection.setRequestProperty(HttpHeaders.AUTHORIZATION, "key=" + this.fcmKey);
            connection.setDoOutput(true);

            PushMessage push = new PushMessage();
            push.setTo(devToken);
            Data data = new Data();
            data.setBody(message);
            data.setTitle(messageTitle);
            push.setData(data);

            Notification notification = new Notification();
            notification.setBody(message);
            notification.setTitle(messageTitle);
            push.setNotification(notification);
            Gson gson = new Gson();
            String payload = gson.toJson(push);
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = payload.getBytes(UTF_8);
                os.write(input, 0, input.length);
            }

            try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                PushResponse pr = gson.fromJson(response.toString(), PushResponse.class);
                model.addAttribute("prSuccess", pr.getSuccess());
                model.addAttribute("multicastId", pr.getMulticast_id());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "sendpushform";
    }
}