package com.worth.ifs.token.transactional;

import com.fasterxml.jackson.databind.JsonNode;
import com.worth.ifs.application.transactional.ApplicationService;
import com.worth.ifs.token.domain.Token;
import com.worth.ifs.token.repository.TokenRepository;
import com.worth.ifs.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
@Transactional
public class TokenServiceImpl implements TokenService{

    @Autowired
    TokenRepository repository;
    @Autowired
    ApplicationService applicationService;


    @Override
    public Optional<Token> getTokenByHash(String hash){
        return repository.findByHash(hash);
    }

    @Override
    public void removeToken(Token token){
        repository.delete(token);
    }

    /**
     *  if there are extra attributes in the token, then maybe we need to create a new application, or add the user to a application.
     */
    @Override
    public void handleExtraAttributes(Token token){
        JsonNode extraInfo = token.getExtraInfo();
        if(User.class.getName().equals(token.getClassName()) && extraInfo.has("competitionId") && extraInfo.get("competitionId").isLong()){
            Long competitionId = extraInfo.get("competitionId").asLong();
            if(competitionId != null){
                applicationService.createApplicationByApplicationNameForUserIdAndCompetitionId(competitionId, token.getClassPk(), "");
            }
        }
    }
}

@@ -287,16 +287,101 @@
 n.User;%0A
+import org.apache.commons.logging.Log;%0Aimport org.apache.commons.logging.LogFactory;%0A
 import o
@@ -654,16 +654,94 @@
 Service%7B
+%0A    private static final Log LOG = LogFactory.getLog(TokenServiceImpl.class);
 %0A%0A    @A
@@ -1424,51 +1424,8 @@
 Id%22)
- && extraInfo.get(%22competitionId%22).isLong()
 )%7B%0A 
@@ -1533,16 +1533,39 @@
  != null
+ && competitionId != 0L
 )%7B%0A     

Fix for application creation after clicking verify link