// UserLoginHandler parses the http request and login with an exist user.
// Usage :
//		POST v1/user/login
// If successful,response code will be set to 201.
func (p *Resource) UserLoginHandler(req *restful.Request, resp *restful.Response) {
	logrus.Infof("UserLoginHandler is called!")

	doc := bson.M{}
	decoder := json.NewDecoder(req.Request.Body)
	err := decoder.Decode(&doc)
	if err != nil {
		logrus.Errorf("decode user err is %v", err)
		response.WriteStatusError(services.USER_ERROR_LOGIN, err, resp)
		return
	}
	username, password, paraErr := userLoginParamCheck(doc)
	if paraErr != nil {
		response.WriteStatusError(services.COMMON_ERROR_INVALIDATE, paraErr, resp)
		return
	}

	if len(username) == 0 || len(password) == 0 {
		logrus.Errorf("username and password can not be null!")
		response.WriteStatusError(services.COMMON_ERROR_INVALIDATE, errors.New("Username or password can not be null"), resp)
		return
	}

	errorCode, loginRes, err := services.GetUserService().UserLogin(username, password)
	if err != nil {
		response.WriteStatusError(errorCode, err, resp)
		return
	}

	response.WriteResponse(loginRes, resp)

	return

}
// TokenCreateHandler parses the http request and create a new user token.
// Usage :
//		POST /v1/token
// If successful,response code will be set to 201.
func (p *Resource) TokenCreateHandler(req *restful.Request, resp *restful.Response) {
	logrus.Infof("TokenCreateHandler is called!")

	doc := bson.M{}
	decoder := json.NewDecoder(req.Request.Body)
	err := decoder.Decode(&doc)
	if err != nil {
		logrus.Errorf("decode credential err is %v", err)
		response.WriteStatusError(services.TOKEN_ERROR_CREATE, err, resp)
		return
	}

	username, passwd, tenant, paraErr := tokenCreateParamCheck(doc)
	if paraErr != nil {
		response.WriteStatusError(services.COMMON_ERROR_INVALIDATE, paraErr, resp)
		return
	}

	ret, errorCode, err := services.GetTokenService().TokenCreate(username, passwd, tenant)
	if err != nil {
		response.WriteStatusError(errorCode, err, resp)
		return
	}

	response.WriteResponse(ret, resp)

	return
}
func (p *Resource) TenantIdHandler(req *restful.Request, resp *restful.Response) {
	logrus.Infoln("TenantIdHandler is called!")

	token := req.HeaderParameter("X-Auth-Token")
	userId := req.QueryParameter("userId")

	ret, errorCode, err := services.GetTenantService().GetTenantId(token, userId)
	if err != nil {
		response.WriteStatusError(errorCode, err, resp)
		return
	}

	response.WriteResponse(ret, resp)
}
func (p *Resource) successUpdate(id string, created bool, req *restful.Request, resp *restful.Response) {
	// Updated document API location
	docpath := documentLocation(req, id)

	// Content-Location header
	resp.AddHeader("Content-Location", docpath)

	// Information about updated document
	info := response.UpdateStruct{created, docpath}

	if created {
		response.WriteResponseStatus(http.StatusCreated, info, resp)
	} else {
		response.WriteResponse(info, resp)
	}
}
func (p *Resource) UserDetailHandler(req *restful.Request, resp *restful.Response) {
	logrus.Infof("UserDetailHandler is called!")

	token := req.HeaderParameter("X-Auth-Token")
	id := req.PathParameter(ParamID)
	if len(id) <= 0 {
		logrus.Warnln("user id should not be null for user detail operation")
		response.WriteStatusError(services.COMMON_ERROR_INVALIDATE, errors.New("user id should not be null for get user operation"), resp)
		return
	}

	ret, errorCode, err := services.GetUserService().UserDetail(token, id)
	if err != nil {
		response.WriteStatusError(errorCode, err, resp)
		return
	}

	response.WriteResponse(ret, resp)
}
func (p *Resource) TenantDetailHandler(req *restful.Request, resp *restful.Response) {
	logrus.Infof("TenantDetailHandler is called!")

	token := req.HeaderParameter("X-Auth-Token")
	id := req.PathParameter(ParamID)
	if len(id) <= 0 {
		logrus.Warnln("tenant id should not be null for tenant detail operation")
		response.WriteStatusError(services.TENANT_ERROR_GET, errors.New("tenant id should not be null for get tenant operation"), resp)
		return
	}

	ret, errorCode, err := services.GetTenantService().TenantDetail(token, id)
	if err != nil {
		response.WriteStatusError(errorCode, err, resp)
		return
	}

	response.WriteResponse(ret, resp)
}
// TokenReGenerateHandler parses the http request and generate
// another user's token from current token.
// Usage :
//		POST /v1/token/regenerate
// If successful,response code will be set to 201.
func (p *Resource) TokenReGenerateHandler(req *restful.Request, resp *restful.Response) {
	logrus.Infoln("TokenReGenerateHandler is called!")
	token := req.HeaderParameter("X-Auth-Token")

	document := bson.M{}
	decoder := json.NewDecoder(req.Request.Body)
	err := decoder.Decode(&document)
	if err != nil {
		logrus.Errorf("decode token generate err is %v", err)
		response.WriteStatusError(services.TOKEN_ERROR_CREATE, err, resp)
		return
	}

	document, err = mejson.Unmarshal(document)
	if err != nil {
		logrus.Errorf("unmarshal token generate err is %v", err)
		response.WriteStatusError(services.TOKEN_ERROR_CREATE, err, resp)
		return
	}

	userid := document["user_id"]
	tenantid := document["tenant_id"]
	if userid == nil || tenantid == nil {
		logrus.Errorln("invalid parameter! user and tenant should not be null!")
		response.WriteStatusError(services.COMMON_ERROR_INVALIDATE, errors.New("invalid parameter! user and tenant should not be null!"), resp)
		return
	}

	tokenId, errorCode, err := services.GetTokenService().TokenReGenerate(token, userid.(string), tenantid.(string))
	if err != nil {
		response.WriteStatusError(errorCode, err, resp)
		return
	}

	response.WriteResponse(tokenId, resp)

	return
}