package next.operator.user.dao;

import com.linecorp.bot.client.LineMessagingClient;
import com.linecorp.bot.model.event.source.GroupSource;
import com.linecorp.bot.model.event.source.RoomSource;
import com.linecorp.bot.model.event.source.Source;
import com.linecorp.bot.model.profile.UserProfileResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

@Component
public class UserDao {

  @Autowired
  private LineMessagingClient client;

  public ThreadLocal<String> currentUserName = new ThreadLocal<>();
  public ThreadLocal<Source> currentSource = new ThreadLocal<>();

  public String getCurrentUserName() {

    if (currentUserName.get() != null) {
      return currentUserName.get();
    } else {
      final Source source = currentSource.get();
      final CompletableFuture<UserProfileResponse> userProfileResponse;
      if (source instanceof RoomSource) {
        userProfileResponse = client.getRoomMemberProfile(((RoomSource) source).getRoomId(), source.getUserId());
      } else if (source instanceof GroupSource) {
        userProfileResponse = client.getGroupMemberProfile(((GroupSource) source).getGroupId(), source.getUserId());
      } else {
        userProfileResponse = client.getProfile(source.getUserId());
      }

      String displayName;
      try {
        displayName = userProfileResponse.get().getDisplayName();
      } catch (Exception ignore) {
        displayName = "";
      }
      currentUserName.set(displayName);
      return displayName;
    }

  }

  public void clear() {
    currentSource.remove();
    currentUserName.remove();
  }
}

@@ -808,24 +808,64 @@
    %7D else %7B%0A
+      String displayName;%0A      try %7B%0A  
       final 
@@ -897,24 +897,26 @@
 urce.get();%0A
+  
       final 
@@ -977,24 +977,26 @@
 onse;%0A      
+  
 if (source i
@@ -1011,32 +1011,34 @@
 f RoomSource) %7B%0A
+  
         userProf
@@ -1137,24 +1137,26 @@
 d());%0A      
+ 
+ 
 %7D else if (s
@@ -1179,32 +1179,34 @@
  GroupSource) %7B%0A
+  
         userProf
@@ -1308,24 +1308,26 @@
 d());%0A      
+  
 %7D else %7B%0A   
@@ -1323,32 +1323,34 @@
  else %7B%0A        
+ 
+ 
 userProfileRespo
@@ -1404,48 +1404,11 @@
     
-%7D%0A%0A      String displayName;%0A      try %7B
+  %7D
 %0A   

fix 保底判定