/*
 * Queue - A Queueing system that can be used to handle labs in higher education
 * Copyright (C) 2016-2021  Delft University of Technology
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
package nl.tudelft.queue.controller;

import nl.martijndwars.webpush.PushService;
import nl.martijndwars.webpush.Utils;
import nl.tudelft.labracore.lib.security.user.AuthenticatedPerson;
import nl.tudelft.labracore.lib.security.user.Person;
import nl.tudelft.queue.dto.create.SubscriptionCreateDTO;
import nl.tudelft.queue.realtime.SubscriptionContainer;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.interfaces.ECPublicKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/push")
public class PushController {
	@Autowired
	private SubscriptionContainer sc;

	@Autowired
	private PushService ps;

	/**
	 * Gets the public VAPID key generated for this server.
	 *
	 * @return The generated VAPID key in Base64 url encoding.
	 */
	@Cacheable("public-vapid-key")
	@GetMapping("/public-vapid-key")
	public String getPublicVapidKey() {
		return Base64.encodeBase64URLSafeString(Utils.encode((ECPublicKey) ps.getPublicKey()));
	}

	/**
	 * Sets the subscription for the current session.
	 *
	 * @param dto The dto to convert into a subscription.
	 */
	@PostMapping("/subscribe")
	public void subscribePushEndpoint(@AuthenticatedPerson Person person,
			SubscriptionCreateDTO dto) {
		dto.setPerson(person.getId());

		sc.update(dto);
	}
}
