package com.wecloud.im.sdk.internal;

import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wecloud.im.sdk.common.HttpMethod;
import com.wecloud.im.sdk.common.RequestMessage;
import com.wecloud.im.sdk.model.Blacklist;
import com.wecloud.im.sdk.model.ChatRoomMember;
import com.wecloud.im.sdk.model.ClientLoginRequest;
import com.wecloud.im.sdk.model.Conversation;
import com.wecloud.im.sdk.model.Friend;
import com.wecloud.im.sdk.model.FriendRequestRequest;
import com.wecloud.im.sdk.model.GetFriendsRequest;
import com.wecloud.im.sdk.model.GetUnsureFriendsRequest;
import com.wecloud.im.sdk.model.ImClient;
import com.wecloud.im.sdk.model.ListChatRoomMemberRequest;
import com.wecloud.im.sdk.model.ListConversationRequest;
import com.wecloud.im.sdk.model.ModifyUserRequest;
import com.wecloud.im.sdk.model.PageBlacklistRequest;
import com.wecloud.im.sdk.model.PageResult;
import com.wecloud.im.sdk.model.RegisterClientRequest;
import com.wecloud.im.sdk.model.Token;
import com.wecloud.im.sdk.model.UnsureFriend;

import static com.wecloud.im.sdk.ResourcePathConstants.FRIEND_REQUEST;
import static com.wecloud.im.sdk.ResourcePathConstants.GET_FRIENDS;
import static com.wecloud.im.sdk.ResourcePathConstants.GET_TOKEN_URL;
import static com.wecloud.im.sdk.ResourcePathConstants.GET_UNSURE_FRIENDS;
import static com.wecloud.im.sdk.ResourcePathConstants.LIST_CHAT_ROOM_MEMBER_REQUEST;
import static com.wecloud.im.sdk.ResourcePathConstants.LIST_CONVERSATION_REQUEST;
import static com.wecloud.im.sdk.ResourcePathConstants.MODIFY_USER_URL;
import static com.wecloud.im.sdk.ResourcePathConstants.PAGE_BLACKLIST_REQUEST;
import static com.wecloud.im.sdk.ResourcePathConstants.REGISTER_CLIENT_URL;
import static com.wecloud.im.sdk.utils.CodingUtils.assertParameterNotBlank;
import static com.wecloud.im.sdk.utils.CodingUtils.assertParameterNotNull;

/**
 * client
 * @Author luozh
 * @Date 2022年04月13日 15:26
 * @Version 1.0
 */
public class WecloudImClientOperation extends WecloudImOperation {

    public WecloudImClientOperation(URL apiDomain, String appKey, String appSecret) {
        super(apiDomain, appKey, appSecret);
    }

    /**
     * 注册客户端
     * @Author luozh
     * @Date 2022年04月13日 03:38:58
     * @param registerClientRequest
     * @Return
     */
    public ImClient registerClient(RegisterClientRequest registerClientRequest) {
        String userId = registerClientRequest.getUserId();
        // 参数校验
        assertParameterNotNull(userId, "userId");
        // 校验通过 构建参数
        Map<String, String> param = new HashMap<>();
        param.put("userId", registerClientRequest.getUserId() + "");
        param.put("headPortrait", Optional.ofNullable(registerClientRequest.getHeadPortrait()).orElse(""));
        param.put("nickname", Optional.ofNullable(registerClientRequest.getNickname()).orElse(""));
        // 发送请求
        RequestMessage request = new WecloudRequestMessageBuilder().setEndpoint(REGISTER_CLIENT_URL)
                .setMethod(HttpMethod.POST).setParameters(param)
                .setOriginalRequest(registerClientRequest).build();

        Object result = doOperation(request);
        ImClient imClient = JSON.parseObject(JSON.toJSONString(result), ImClient.class);
        return imClient;
    }

    /**
     * 获取用户token
     * @Author luozh
     * @Date 2022年04月18日 11:52:18
     * @param clientLoginRequest
     * @Return
     */
    public Token getToken(ClientLoginRequest clientLoginRequest) {
        String clientId = clientLoginRequest.getClientId();
        Integer deviceType = clientLoginRequest.getDeviceType();
        // 参数校验
        assertParameterNotNull(clientId, "userId");
        assertParameterNotNull(deviceType, "deviceType");
        // 校验通过 构建参数
        Map<String, String> param = new HashMap<>();
        param.put("deviceType", clientLoginRequest.getDeviceType() + "");
        param.put("clientId", clientLoginRequest.getClientId() + "");

        // 发送请求
        RequestMessage request = new WecloudRequestMessageBuilder().setEndpoint(GET_TOKEN_URL)
                .setMethod(HttpMethod.POST).setParameters(param)
                .setOriginalRequest(clientLoginRequest).build();

        Object result = doOperation(request);
        Token token = JSON.parseObject(JSON.toJSONString(result), Token.class);
        return token;
    }

    /**
     * 修改用户
     * @Author luozh
     * @Date 2022年04月18日 03:31:04
     * @param modifyUserRequest
     * @Return
     */
    public Boolean modifyUser(ModifyUserRequest modifyUserRequest) {
        String userId = modifyUserRequest.getUserId();
        String headPortrait = modifyUserRequest.getHeadPortrait();
        String nickname = modifyUserRequest.getNickname();
        // 参数校验
        assertParameterNotNull(userId, "userId");
        assertParameterNotBlank(headPortrait, "headPortrait");
        assertParameterNotBlank(nickname, "headPortrait");
        // 校验通过 构建参数
        Map<String, String> param = new HashMap<>();
        param.put("userId", userId + "");
        param.put("headPortrait", headPortrait);
        param.put("nickname", nickname);
        // 发送请求
        RequestMessage request = new WecloudRequestMessageBuilder().setEndpoint(MODIFY_USER_URL)
                .setMethod(HttpMethod.POST).setParameters(param)
                .setOriginalRequest(modifyUserRequest).build();

        Object result = doOperation(request);
        Boolean flag = JSON.parseObject(JSON.toJSONString(result), Boolean.class);
        return flag;
    }

    /**
     * 待接受的好友请求列表
     * @Author luozh
     * @Date 2022年04月21日 05:08:13
     * @param getUnsureFriendsRequest
     * @Return
     */
    public List<UnsureFriend> getUnsureFriends(GetUnsureFriendsRequest getUnsureFriendsRequest) {
        String userId = getUnsureFriendsRequest.getUserId();
        // 参数校验
        assertParameterNotNull(userId, "userId");
        // 校验通过 构建参数
        Map<String, String> param = new HashMap<>();
        param.put("clientId", userId + "");

        // 发送请求
        RequestMessage request = new WecloudRequestMessageBuilder().setEndpoint(GET_UNSURE_FRIENDS)
                .setMethod(HttpMethod.GET).setParameters(param)
                .setOriginalRequest(getUnsureFriendsRequest).build();

        Object result = doOperation(request);
        TypeReference<List<UnsureFriend>> typeReference = new TypeReference<List<UnsureFriend>>() {
        };
        List<UnsureFriend> unsureFriends = JSON.parseObject(JSON.toJSONString(result), typeReference);
        return unsureFriends;
    }

    /**
     * 获取好友列表(全量)
     * @Author luozh
     * @Date 2022年04月28日 03:01:21
     * @param getFriendsRequest
     * @Return
     */
    public List<Friend> getFriends(GetFriendsRequest getFriendsRequest) {
        String userId = getFriendsRequest.getUserId();
        // 参数校验
        assertParameterNotNull(userId, "userId");
        // 校验通过 构建参数
        Map<String, String> param = new HashMap<>();
        param.put("clientId", userId + "");
        // 发送请求
        RequestMessage request = new WecloudRequestMessageBuilder().setEndpoint(GET_FRIENDS)
                .setMethod(HttpMethod.GET).setParameters(param)
                .setOriginalRequest(getFriendsRequest).build();

        Object result = doOperation(request);
        TypeReference<List<Friend>> typeReference = new TypeReference<List<Friend>>() {
        };
        List<Friend> unsureFriends = JSON.parseObject(JSON.toJSONString(result), typeReference);
        return unsureFriends;
    }

    /**
     * 好友请求
     * @Author luozh
     * @Date 2022年04月28日 03:01:47
     * @param friendRequestRequest
     */
    public Boolean friendRequest(FriendRequestRequest friendRequestRequest) {
        String userId = friendRequestRequest.getUserId();
        String friendId = friendRequestRequest.getFriendId();
        // 参数校验
        assertParameterNotNull(userId, "userId");
        assertParameterNotNull(friendId, "friendId");
        // 校验通过 构建参数
        Map<String, String> param = new HashMap<>();
        param.put("clientId", userId + "");
        param.put("friendClientId", friendId + "");
        param.put("friendName", Optional.ofNullable(friendRequestRequest.getFriendName()).orElse(""));
        param.put("requestRemark", Optional.ofNullable(friendRequestRequest.getRequestRemark()).orElse(""));
        // 发送请求
        RequestMessage request = new WecloudRequestMessageBuilder().setEndpoint(FRIEND_REQUEST)
                .setMethod(HttpMethod.POST).setParameters(param)
                .setOriginalRequest(friendRequestRequest).build();
        Object result = doOperation(request);
        Boolean flag = JSON.parseObject(JSON.toJSONString(result), Boolean.class);
        return flag;
    }

    public List<ChatRoomMember> listChatRoomMember(ListChatRoomMemberRequest listChatRoomMemberRequest) {
        // 参数校验
        assertParameterNotNull(listChatRoomMemberRequest.getChatRoomId(), "chatRoomId");
        // 校验通过 构建参数
        Map<String, String> param = new HashMap<>();
        param.put("chatRoomId", listChatRoomMemberRequest.getChatRoomId() + "");
        // 发送请求
        RequestMessage request = new WecloudRequestMessageBuilder().setEndpoint(LIST_CHAT_ROOM_MEMBER_REQUEST)
                .setMethod(HttpMethod.POST).setParameters(param)
                .setOriginalRequest(listChatRoomMemberRequest).build();

        Object result = doOperation(request);
        TypeReference<List<ChatRoomMember>> typeReference = new TypeReference<List<ChatRoomMember>>() {
        };
        List<ChatRoomMember> chatRoomMembers = JSON.parseObject(JSON.toJSONString(result), typeReference);
        return chatRoomMembers;
    }

    public List<Conversation> listConversation(ListConversationRequest listConversationRequest) {
        // 参数校验
        assertParameterNotNull(listConversationRequest.getConversationIds(), "conversationIds");
        // 校验通过 构建参数
        Map<String, String> param = new HashMap<>();
        param.put("chatType", listConversationRequest.getChatType() + "");
        param.put("conversationIds", JSON.toJSONString(listConversationRequest.getConversationIds()));
        // 发送请求
        RequestMessage request = new WecloudRequestMessageBuilder().setEndpoint(LIST_CONVERSATION_REQUEST)
                .setMethod(HttpMethod.POST).setParameters(param)
                .setOriginalRequest(listConversationRequest).build();

        Object result = doOperation(request);
        TypeReference<List<Conversation>> typeReference = new TypeReference<List<Conversation>>() {
        };
        List<Conversation> conversations = JSON.parseObject(JSON.toJSONString(result), typeReference);
        return conversations;
    }

    public PageResult<Blacklist> pageBlacklist(PageBlacklistRequest pageBlacklistRequest) {
        // 参数校验
        assertParameterNotNull(pageBlacklistRequest.getUserId(), "userId");
        // 校验通过 构建参数
        if (pageBlacklistRequest.getPageIndex() == null) {
            pageBlacklistRequest.setPageIndex(1);
        }
        if (pageBlacklistRequest.getPageSize() == null) {
            pageBlacklistRequest.setPageSize(10);
        }
        Map<String, String> param = new HashMap<>();
        param.put("clientId", pageBlacklistRequest.getUserId());
        param.put("pageIndex", pageBlacklistRequest.getPageIndex() + "");
        param.put("pageSize", pageBlacklistRequest.getPageSize() + "");
        // 发送请求
        RequestMessage request = new WecloudRequestMessageBuilder().setEndpoint(PAGE_BLACKLIST_REQUEST)
                .setMethod(HttpMethod.POST).setParameters(param)
                .setOriginalRequest(pageBlacklistRequest).build();

        Object result = doOperation(request);
        TypeReference<PageResult<Blacklist>> typeReference = new TypeReference<PageResult<Blacklist>>() {
        };
        PageResult<Blacklist> blacklistPage = JSON.parseObject(JSON.toJSONString(result), typeReference);
        return blacklistPage;


    }
}
