package org.telegram.tgnet;


import android.util.Log;

import org.telegram.io.Caller;

import java.util.concurrent.atomic.AtomicInteger;

public class ConnectionsManager {


    private int currentAccount = 0;

    public static Caller caller = null;
    public static String defaultIp = "127.0.0.1";


    public ConnectionsManager() {


        native_init(0, 1358, 85, 41962, "OnePlusA0001", "OnePlusA0001", "4.9.1 (13580)", "us", "us", "/data/user/0/org.telegram.messenger.beta/files", "", 0, true, true, 0);
    }


    public long checkProxy(String address, int port, String secret, RequestTimeDelegate requestTimeDelegate) {

        return native_checkProxy(currentAccount, address, port, "", "", secret, requestTimeDelegate);
    }


    public static void setProxySettings(String address, int port, String secret) {


        native_setProxySettings(0, address, port, "", "", secret);


    }

    public static native void native_switchBackend(int currentAccount);

    public static native int native_isTestBackend(int currentAccount);

    public static native void native_pauseNetwork(int currentAccount);

    public static native void native_setUseIpv6(int currentAccount, boolean value);

    public static native void native_updateDcSettings(int currentAccount);

    public static native void native_setNetworkAvailable(int currentAccount, boolean value, int networkType, boolean slow);

    public static native void native_resumeNetwork(int currentAccount, boolean partial);

    public static native long native_getCurrentTimeMillis(int currentAccount);

    public static native int native_getCurrentTime(int currentAccount);

    public static native int native_getTimeDifference(int currentAccount);

    public static native void native_sendRequest(int currentAccount, long object, RequestDelegateInternal onComplete, QuickAckDelegate onQuickAck, WriteToSocketDelegate onWriteToSocket, int flags, int datacenterId, int connetionType, boolean immediate, int requestToken);

    public static native void native_cancelRequest(int currentAccount, int token, boolean notifyServer);

    public static native void native_cleanUp(int currentAccount, boolean resetKeys);

    public static native void native_cancelRequestsForGuid(int currentAccount, int guid);

    public static native void native_bindRequestToGuid(int currentAccount, int requestToken, int guid);

    public static native void native_applyDatacenterAddress(int currentAccount, int datacenterId, String ipAddress, int port);

    public static native int native_getConnectionState(int currentAccount);

    public static native void native_setUserId(int currentAccount, int id);

    public static native void native_init(int currentAccount, int version, int layer, int apiId, String deviceModel, String systemVersion, String appVersion, String langCode, String systemLangCode, String configPath, String logPath, int userId, boolean enablePushConnection, boolean hasNetwork, int networkType);

    public static native void native_setProxySettings(int currentAccount, String address, int port, String username, String password, String secret);

    public static native void native_setLangCode(int currentAccount, String langCode);

    public static native void native_setJava(boolean useJavaByteBuffers);

    public static native void native_setPushConnectionEnabled(int currentAccount, boolean value);

    public static native void native_applyDnsConfig(int currentAccount, long address, String phone);

    public static native long native_checkProxy(int currentAccount, String address, int port, String username, String password, String secret, RequestTimeDelegate requestTimeDelegate);


    public static boolean isRoaming() {

        return false;
    }

    public static boolean isConnectedOrConnectingToWiFi() {

        return false;
    }

    public static boolean isConnectedToWiFi() {

        return false;
    }

    public final static int RequestFlagEnableUnauthorized = 1;
    public final static int RequestFlagFailOnServerErrors = 2;
    public final static int RequestFlagCanCompress = 4;
    public final static int RequestFlagWithoutLogin = 8;
    public final static int RequestFlagTryDifferentDc = 16;
    public final static int RequestFlagForceDownload = 32;
    public final static int RequestFlagInvokeAfter = 64;
    public final static int RequestFlagNeedQuickAck = 128;

    public void setAppPaused(final boolean value, final boolean byScreenState) {


    }

    public static void onUnparsedMessageReceived(long address, final int currentAccount) {

    }

    public static void onUpdate(final int currentAccount) {

    }

    public final static int DEFAULT_DATACENTER_ID = Integer.MAX_VALUE;
    public final static int ConnectionTypeGeneric = 1;

    public static int sendRequest() {
        final TLRPC.TL_auth_signIn req = new TLRPC.TL_auth_signIn();
        req.phone_number = "9371455245";
        req.phone_code = "98";
        req.phone_code_hash = "0";


        return sendRequest(req, new RequestDelegate() {
            @Override
            public void run(TLObject response, TLRPC.TL_error error) {

            }
        }, null, null, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin, DEFAULT_DATACENTER_ID, ConnectionTypeGeneric, true);
    }

    public static int sendRequest(final TLObject object, final RequestDelegate onComplete, final QuickAckDelegate onQuickAck, final WriteToSocketDelegate onWriteToSocket, final int flags, final int datacenterId, final int connetionType, final boolean immediate) {
        String ip = defaultIp;
        AtomicInteger lastRequestToken = new AtomicInteger(1);
        final int requestToken = lastRequestToken.getAndIncrement();



        try {
            NativeByteBuffer buffer = new NativeByteBuffer(object.getObjectSize());
            object.serializeToStream(buffer);
            object.freeResources();

            native_sendRequest(0, buffer.address, (response, errorCode, errorText, networkType) -> {

                if (defaultIp.equals(ip))
                {
                    if (caller != null) {
                        caller.status(0);
                    } else {
                        Log.e("Ip Caller", "Null");
                    }
                }
            }, onQuickAck, onWriteToSocket, flags, datacenterId, connetionType, immediate, requestToken);
        } catch (Exception e) {
            // FileLog.e(e);
        }

        return requestToken;
    }


    public static int getCurrentNetworkType() {
        return 0;
    }


    protected static boolean useIpv6Address() {
        return false;
    }


    public static boolean isNetworkOnline() {
        return true;
    }

    public static void setLangCode(String langCode) {

    }


    public static void onSessionCreated(final int currentAccount) {

    }

    public static void onConnectionStateChanged(final int state, final int currentAccount) {
        if (state == 3) {
            // Log.e("Ip Status Must", String.valueOf(state));
            sendRequest();

        }


    }


    public static void setCaller(Caller clr) {
        caller = clr;
    }

    public static void onLogout(final int currentAccount) {

    }


    public static int getInitFlags() {
        return 0;
    }

    public static void onBytesSent(int amount, int networkType, final int currentAccount) {

    }

    public static void onRequestNewServerIpAndPort(final int second, final int currentAccount) {

    }

    public static void onProxyError() {

    }

    public static String getHostByName(String domain, final int currentAccount) {

        return "";
    }

    public static void onBytesReceived(int amount, int networkType, final int currentAccount) {

    }

    public static void onUpdateConfig(long address, final int currentAccount) {

    }

    public static void onInternalPushReceived(final int currentAccount) {

    }

}
