/*******************************************************************************
 * Copyright 2Fi Business Solutions Ltd.
 *
 * This code is copyrighted. Under no circumstances should any party, people,
 * or organization should redistribute any portions of this code in any form,
 * either verbatim or through electronic media, to any third parties, unless
 * under explicit written permission by 2Fi Business Solutions Ltd.
 ******************************************************************************/
package com.ffii.tbms.api.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.ffii.core.utils.MapUtils;
import com.ffii.core.utils.NumberUtils;
import com.ffii.core.utils.Params;
import com.ffii.core.web.AbstractController;
import com.ffii.core.web.view.json.JsonView;
import com.ffii.tbms.api.service.AuthenticationService;
import com.ffii.tbms.user.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Authentication API Controller
 *
 * @author Patrick
 */
@Controller
@RequestMapping(value = "/api")
public class AuthenticationController extends AbstractController {

	private static final StandardPasswordEncoder PASSWORD_ENCODER = new StandardPasswordEncoder();

	@Autowired
	private AuthenticationService authenticationService;

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/auth", method = { RequestMethod.GET, RequestMethod.POST })
	public String auth(Model model, @RequestParam String deviceId, @RequestParam String username,
			@RequestParam String password, HttpServletRequest request) throws Exception {

		Map<String, Object> data = userService.findUserMap(MapUtils.toHashMap("username", username));

		if (data != null) {
			String encodedPassword = (String) data.get("password");

			boolean matches = PASSWORD_ENCODER.matches(password, encodedPassword);

			// if password matches
			if (matches) {
				int userId = NumberUtils.intValue(data.get("id"));
				String token = authenticationService.createAccessToken(userId, deviceId);
				model.addAttribute("token", token);
				model.addAttribute("id", data.get("id"));
				model.addAttribute("firstname", data.get("firstname"));
				model.addAttribute("lastname", data.get("lastname"));
				model.addAttribute("fullname", data.get("fullname"));
			}
			model.addAttribute(Params.SUCCESS, matches);
		} else {
			model.addAttribute(Params.SUCCESS, Boolean.FALSE);
		}

		return JsonView.NAME;
	}

}