package org.bench4q.master.unitTest.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBException;

import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.AuthorizeResponseModel;
import org.bench4q.share.models.master.RegisterResponseModel;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class UserControllerTest extends TestBase {
	@Before
	public void prepare() {
		this.setAccessTocken(this.login());
	}

	@Test
	public void testNormalAuth() throws IOException, JAXBException {
		String urlString = BASE_URL
				+ "/user/normalAuthorize?userName=chen&password=123";
		HttpResponse httpResponse = this.httpRequester.sendGet(urlString, null,
				null);
		AuthorizeResponseModel ret = (AuthorizeResponseModel) MarshalHelper
				.unmarshal(AuthorizeResponseModel.class,
						httpResponse.getContent());
		assertTrue(ret.isSuccess());
	}

	@Test
	public void testAdminAuth() throws IOException, JAXBException {
		String url = BASE_URL
				+ "/user/adminAuthorize?userName=chen&password=123";
		HttpResponse httpResponse = this.httpRequester.sendGet(url, null, null);
		AuthorizeResponseModel ret = (AuthorizeResponseModel) MarshalHelper
				.unmarshal(AuthorizeResponseModel.class,
						httpResponse.getContent());
		assertTrue(ret.isSuccess());
	}

	@Test
	public void testAdminRegister() throws IOException {
		String userName = "test";
		clearUser(userName);
		String url = BASE_URL + "/user/register";
		Map<String, String> params = new HashMap<String, String>();

		params.put("userName", userName);
		params.put("password", "test");
		params.put("scope", "1");
		HttpResponse httpResponse = this.httpRequester.sendGet(url, params,
				null);
		RegisterResponseModel registerResponseModel = (RegisterResponseModel) MarshalHelper
				.tryUnmarshal(RegisterResponseModel.class,
						httpResponse.getContent());
		assertNotNull(registerResponseModel);
		assertTrue(registerResponseModel.isSuccess());
		assertTrue(clearUser(userName).isSuccess());

	}

	private AuthorizeResponseModel clearUser(String userName)
			throws IOException {
		String url = BASE_URL + "/user/deleteUser" + "/" + userName;
		HttpResponse httpResponse = this.httpRequester.sendGet(url, null, null);
		System.out.println(httpResponse.getContent());
		AuthorizeResponseModel authorizeResponseModel = (AuthorizeResponseModel) MarshalHelper
				.tryUnmarshal(AuthorizeResponseModel.class,
						httpResponse.getContent());

		return authorizeResponseModel;
	}
}
