package tv.twitch.twiglib;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import tv.twitch.chat.ChatChannelInfo;
import tv.twitch.chat.ChatFirstTimeChatterNotice;
import tv.twitch.chat.ChatLiveMessage;
import tv.twitch.chat.ChatMessageToken;
import tv.twitch.chat.ChatMessageTokenType;
import tv.twitch.chat.ChatRaidNotice;
import tv.twitch.chat.ChatSubscriptionNotice;
import tv.twitch.chat.ChatTextToken;
import tv.twitch.chat.ChatUnraidNotice;
import tv.twitch.chat.ChatUserInfo;
import tv.twitch.sdk.*;
import tv.twitch.*;

import com.unity3d.player.*;

public class TwigTest {
    private static String TAG = "Twitch_Test";
    SDKHttpRequestProvider sdkHttpRequestProvider;

    UserInfo mUserInfo;
    ChatController mChatController;
    ChannelListener mChannelListener;

    TwigTest(){
        SDKServicesController.setClientId("dviaxdls39mj44cdnei76mj2dlig33");
        sdkHttpRequestProvider = new SDKHttpRequestProvider(UnityPlayer.currentActivity.getApplication());
        mChannelListener = new ChannelListener();
        Logger.d("TwigTest Constructed!");
    }

    public static String GetLibName(){
        return "tv.twitch.twiglib";
    }

    public void SendHttpRequest(){
        HttpParameter httpParameter = new HttpParameter();
        httpParameter.name = "Client-ID";
        httpParameter.value = "1gn5s0jtn8hd6mapt01f72uuo11gao";
        HttpParameter[] httpParameters = {httpParameter};
        HttpRequestResult httpRequestResult = new HttpRequestResult();
        ErrorCode ec = sdkHttpRequestProvider.sendHttpRequest("https://api.twitch.tv/helix/users?login=sehilllo",
                httpParameters,
                null,
                "GET",
                5,
                httpRequestResult);
        Logger.d("Sent HttpRequest: " + httpRequestResult.response);
    }

    public void Initialize() {
        Logger.d("TwigTest start!");
        mChatController = SDKServicesController.getInstance().getChat();
    }

    public void SetLocalLanguage(){
        SDKServicesController.getInstance().setLocalLanguage(Locale.getDefault().getLanguage());
    }

    public void FetchUser(){
        ErrorCode ec = SDKServicesController.getInstance().fetchUserInfo("twiggieg", mApiFetchUserCallback);
        Logger.d(TAG, "FetchUser: " + ec.getName());
    }

    public void Login(){
        boolean hasLogin = SDKServicesController.getInstance().logIn("0h5oyj6s9v39gazh7o6wnwxhjsvdy6", mApiLoginCallback);
        if(hasLogin)
            Logger.d("Has login");
    }

    public void Logout(){
        SDKServicesController.getInstance().logOut();
    }

    public boolean hasLogin(){
        return SDKServicesController.getInstance().isSdkLoggedIn();
    }

    public String GetVersion(){
        return SDKLibrary.getInstance().getVersion();
    }

    public void ChatConnect(){
        Logger.d(TAG,"Calling ChatConnect for " + mUserInfo.userName);
        mChatController.connect(mUserInfo.userId, mUserInfo.userId, UnityPlayer.currentActivity.getApplication().toString());
        mChatController.addChannelListener(mChannelListener);
    }

    public boolean ChatHasConnected(){
        return mChatController.getChannelState(mUserInfo.userId)== ChatController.ChannelState.Connected;
    }

    public void ChatSendMessage(){
        boolean hasSent = mChatController.sendMessage(mUserInfo.userId, "A message from Android.");
    }

    public void ChatDisconnect(){
        mChatController.disconnect(mUserInfo.userId, mUserInfo.userId, UnityPlayer.currentActivity.getApplication().toString());
    }

    private CoreAPI.LogInCallback mApiLoginCallback = new CoreAPI.LogInCallback() {
        @Override
        public void invoke(ErrorCode ec, UserInfo userInfo) {
            if(ec.failed())
                Logger.e("login failed");
            else{
                String[] scopes = SDKServicesController.getInstance().getSDKScopes();
                String scope = new String();
                for(int i = 0; i < scopes.length; i++) { scope = scope + "," + scopes[i]; }

                Logger.d("Login - " + userInfo.displayName + " " + userInfo.userId + ": " + userInfo.bio + "\nScopes: " + scope);
                mUserInfo = userInfo;
            }
        }
    };

    private CoreAPI.FetchUserInfoCallback mApiFetchUserCallback = new CoreAPI.FetchUserInfoCallback() {
        @Override
        public void invoke(ErrorCode ec, UserInfo userInfo) {
            if(ec.failed())
                Logger.e("FetchUser failed");
            else{
                String[] scopes = SDKServicesController.getInstance().getSDKScopes();
                String scope = new String();
                for(int i = 0; i < scopes.length; i++) { scope = scope + "," + scopes[i]; }
            }
        }
    };

    private class ChannelListener implements ChatController.IChannelListener{
        public void onChannelStateChanged(int channelId, ChatController.ChannelState state, ErrorCode ec) {};
        public void onChannelInfoChanged(int channelId, ChatChannelInfo channelInfo){};
        public void onChannelLocalUserChanged(int channelId, ChatUserInfo userInfo){};
        public void onChannelUserChange(int channelId, List<ChatUserInfo> users){};
        public void onChannelMessageReceived(int channelId, ChatLiveMessage[] messageList){
            for(ChatLiveMessage msg : messageList){
                if(msg.messageInfo.displayName.isEmpty())
                    continue;
                String userName = msg.messageInfo.displayName;
                for(ChatMessageToken token : msg.messageInfo.tokens){
                    if(token.type == ChatMessageTokenType.Text){
                        ChatTextToken textToken = (ChatTextToken)token;
                        Logger.d(userName, textToken.text);
                    }
                }
            }
        };
        public void onChannelUserMessagesCleared(int channelId, int userId){};
        public void onChannelMessagesCleared(int channelId){};
        public void onChannelHostTargetChanged(int channelId, String targetChannelName, int numViewers){};
        public void onChannelNoticeReceived(int channelId, String noticeId, HashMap<String, String> params){};
        public void onChannelChatMessageSendError(int channelId, ErrorCode ec){};
        public void onChannelRaidNoticeReceived(int channelId, ChatRaidNotice chatRaidNotice){};
        public void onChannelUnraidNoticeReceived(int channelId, ChatUnraidNotice chatUnraidNotice){};
        public void onChannelFirstTimeChatterNoticeReceived(int channelId, int userId, ChatFirstTimeChatterNotice chatFirstTimeChatterNotice){};
        public void onChannelSubscriptionNoticeReceived(int channelId, int userId, ChatSubscriptionNotice chatSubscriptionNotice){};
    }
}
