package iku.os.ikuterminal;

import static iku.os.net.IkuService.ACTION_STATUS_DESC_CHANGED;
import static iku.os.net.IkuService.ACTION_WEBSOCKET_STATE_RECEIVED;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.google.android.material.textfield.TextInputEditText;

import java.io.File;

import dalvik.system.DexClassLoader;
import iku.os.net.IkuService;
import iku.os.net.PermissionUtil;


public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    protected IkuService mService;

    private boolean websocketConnected = false;

    private static Context context;

    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_STATUS_DESC_CHANGED))
            {
                String msg = intent.getStringExtra("msg");
                TextView statusText = findViewById(R.id.statusText);
                statusText.setText(msg);
            }
            else if (action.equals(ACTION_WEBSOCKET_STATE_RECEIVED))
            {
                boolean connected = intent.getBooleanExtra("connected", false);
                notifyWebsocketState(connected);
            }
        }
    };

    private void notifyWebsocketState(boolean connected)
    {
        websocketConnected = connected;

        Button connectBtn = findViewById(R.id.connectBtn);
        TextInputEditText serverIpInput = findViewById(R.id.serverIpInput);

        if (connected)
        {
            serverIpInput.setEnabled(false);
            connectBtn.setText("断开连接");
        }
        else {
            serverIpInput.setEnabled(true);
            connectBtn.setText("连接");
        }

    }
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG, "onServiceConnected");
            IkuService.WebSocketsBinder binder = (IkuService.WebSocketsBinder) service;
            mService = binder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {Log.i(TAG, "onServiceDisconnected");
            unbindService(mConnection);
            LocalBroadcastManager.getInstance(mService.getApplicationContext()).unregisterReceiver(mMessageReceiver);
            mService = null;
        }
    };
    private ClassLoader dexClassLoader;

    private ClassLoader getDexClassLoader(Class clazz, File file) {
        if (this.dexClassLoader == null)
        {
            this.dexClassLoader = new DexClassLoader(file.getAbsolutePath(), "", null, clazz.getClassLoader());
        }
        return this.dexClassLoader;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        //下载测试
        download();

        TextInputEditText serverIpInput = findViewById(R.id.serverIpInput);
        SharedPreferences sharedPreferences = getSharedPreferences("iku_net_config", MODE_PRIVATE);
        String url = sharedPreferences.getString("ws_url", "");
        serverIpInput.setText(url);

        PermissionUtil.verifyStoragePermissions(this);

        Context context = getApplicationContext();
        File f1 = context.getObbDir();
        File f2 = context.getNoBackupFilesDir();
        String filename = System.mapLibraryName("");
        Log.i("", "");
    }

    public void onClick(View view)
    {
        if (!websocketConnected)
        {
            TextInputEditText serverIpInput = findViewById(R.id.serverIpInput);
            String url = serverIpInput.getEditableText().toString();
            startWebsocket(url);
        }
        else {
            stopWebsocket();
        }

    }
    private void getWebsocketState()
    {
        Intent intent = new Intent(this, IkuService.class);
        intent.setAction(IkuService.ACTION_WEBSOCKET_STATE_GET);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
    private void startWebsocket(String url)
    {
        Intent intent = new Intent(this, IkuService.class);
        intent.setAction(IkuService.ACTION_WEBSOCKET_START);
        intent.putExtra("ws_url", url);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
    private void stopWebsocket()
    {
        Intent intent = new Intent(this, IkuService.class);
        intent.setAction(IkuService.ACTION_WEBSOCKET_STOP);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mService == null)
        {
            Intent intent = new Intent(this, IkuService.class);
            bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
            LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter(ACTION_STATUS_DESC_CHANGED));
            LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter(ACTION_WEBSOCKET_STATE_RECEIVED));
        }
    }

    @Override
    protected void onStop() {
        //unbindService(mConnection);
        //LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
        super.onStop();
    }

    //下载
    private void download() {
        Button testbutton = findViewById(R.id.testBtn);

        testbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, DownloadActivity.class);
                startActivity(intent);
            }
        });
    }


}