/*
 * Licensed to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Jasig licenses this file to you 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 the following location:
 *
 *   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.
 */
package org.jasig.cas.web;

import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.authentication.principal.Credentials;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.jasig.cas.ticket.TicketException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Handles the creation of Ticket Granting Tickets.
 * 
 * @author Scott Battaglia
 * @version $Revision$ $Date$
 * @since 3.3
 * 
 */
@Controller
@RequestMapping(value = "tickets/granting-tickets")
public class TicketGrantingTicketResourceController {

	private static final Logger log = LoggerFactory.getLogger(TicketGrantingTicketResourceController.class);

	@Autowired
	private CentralAuthenticationService centralAuthenticationService;

	public final boolean allowGet() {
		return false;
	}

	public final boolean allowPost() {
		return true;
	}

	@RequestMapping(method = RequestMethod.GET)
	public final ResponseEntity<String> acceptRepresentation(@RequestParam("username") String username, @RequestParam("password") String password)
			throws TicketException {
		if (log.isDebugEnabled()) {
			log.debug("Obtaining credentials...");
		}
		final UsernamePasswordCredentials c1 = new UsernamePasswordCredentials();
		c1.setPassword(password);
		c1.setUsername(username);

		final Credentials c = c1;
		final String ticketGrantingTicketId = this.centralAuthenticationService.createTicketGrantingTicket(c);
		return new ResponseEntity<String>(ticketGrantingTicketId, HttpStatus.OK);
	}

}
