package com.example.plugina;

import android.app.Activity;
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.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.DocumentsContract;
import android.util.ArrayMap;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.bingo.apkloader.base.Apk;
import com.bingo.apkloader.base.ApkConstants;
import com.bingo.apkloader.base.ApkContext;
import com.bingo.apkloader.base.ApkJsInterface;
import com.bingo.apkloader.base.ApkOnActivityResultCallback;
import com.bingo.apkloader.base.ApkWindowBuild;
import com.example.json.JsonFactory;

import java.util.Map;

public class Man implements Apk, ApkJsInterface, ApkOnActivityResultCallback {
    private final static String TAG = "plugina.Man";

    private ApkContext apkContext = null;
    private int testRequestCode = 1001;
    private ServiceConnection serviceConnection;
    private ServiceABinderInterface serviceABinderInterface;
    private final String testAction = "com.bingo.test.apk";
    private BroadcastReceiver broadcastReceiver = null;
    public ApkWindowBuild apkWindowBuilder = null;
    PluginView pluginView = null;

    public static String stringFromJNI(){
        return "hello from java";
    }

    @Override
    public void onCreate(ApkContext apkContext) {
        this.apkContext = apkContext;
        this.apkContext.setJsInterface(this);
        this.apkContext.setPluginOnActivityResultCallback(this);
    }

    @Override
    public void onCreated() {
        Log.d(TAG, "onCreated");

        // 启动service的需要放到onResume中，onCreate中实际还未初始完，所以无法启动
        this.apkContext.startService("com.example.plugina.ServiceA");

        this.apkContext.postDelay(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent();
                intent.setAction(testAction);
                intent.putExtra("from", TAG);
                Man.this.apkContext.sendBroadcast(intent);
            }
        }, 10000);
    }

    @Override
    public void onResume() {
        // onResume
        Log.d(TAG, "onResume--->" + broadcastReceiver);
        if (broadcastReceiver == null){
            broadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    if (intent.getAction().equals(testAction)){
                        Log.e(TAG, "-------->" + testAction + " receiver" + " from = " + intent.getStringExtra("from"));
                    }
                }
            };
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(testAction);
            this.apkContext.registerReceiver(broadcastReceiver, intentFilter);
        }
        if (pluginView != null){
            pluginView.show();
        }
    }

    @Override
    public void onStop() {
        // onStop
        Log.d(TAG, "onStop");
        if (pluginView != null){
            pluginView.hide();
        }
    }

    @Override
    public void onDestroy() {
        // 释放资源
        Log.d(TAG, "释放资源---->" + broadcastReceiver);
        if (broadcastReceiver != null){
            BroadcastReceiver broadcastReceiverTemp = broadcastReceiver;
            broadcastReceiver = null;
            this.apkContext.unregisterReceiver(broadcastReceiverTemp);
        }
        System.gc();
        if (pluginView != null) {
            pluginView.hide();
        }
    }

    @Override
    public void onHandle(String action, Object o) {
        if (ApkConstants.ApkHandleAction.ActionCreateWindowBuilder.equals(action)){
            this.apkWindowBuilder = (ApkWindowBuild) o;
        }
    }

    @Override
    public void call(String action, Map<String, Object> params) {
        Log.d(TAG, "call action = " + action + "-->");
        if ("sayHello".equals(action)){
            Log.d(TAG, "call call sayHello");
            this.sayHello(params);
        }else if ("startPicActivity".equals(action)){
            Log.d(TAG, "call call startPicActivity");
            this.startPicActivity();
        }else if ("bindService".equals(action)){
            bindService(params);
        }else if ("unbindService".equals(action)){
            unbindService();
        }else if ("startActivity".equals(action)){
            startActivity();
        }else if ("initView".equals(action)){
            addView();
        } else if("test".equals(action)) {
            if (pluginView != null) {
                pluginView.hide();
            }
            pluginView = new PluginView(this.apkContext, this.apkWindowBuilder, params);
            pluginView.show();
            ViewPush2 viewPush = new ViewPush2(this.apkWindowBuilder, "rtmp://46.109.1.100:1935", "https://46.109.1.100:18080", "userid", "token", "man", "group", "userid", "vertical");
            View view = viewPush.initView();
            pluginView.updatePluginView(view);
        }else {
            addView();
        }
    }

    @Override
    public void onPluginActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == this.testRequestCode){
            if (resultCode == -1){
                if (data != null && data.getData() != null){
                    Log.d(TAG, "get data and show toast");
                    this.apkContext.showToast(data.getDataString(), 0);
                    return;
                }
            }
        }
        Log.d(TAG, "can not get data");
    }

    private void addView(){
        Log.d(TAG, "call addView ViewPush");
        // 参数pushUrl指定对的推送url
        ViewPush viewPush = new ViewPush(this.apkContext, this.apkWindowBuilder, "rtmp://46.109.1.100:1935", "https://46.109.1.100:18080", "userid", "token", "man", "group", "userid", "vertical");
        viewPush.show();
    }

    private void startActivity(){
        this.apkContext.startActivity("com.example.plugina.ActivityA");
    }

    public void bindService(Map<String, Object> params){
        final int a = Integer.parseInt(params.get("a").toString());
        final int b = Integer.parseInt(params.get("b").toString());
        if (serviceConnection == null) {
            serviceConnection = new ServiceConnection() {
                public void onServiceDisconnected(ComponentName name) {
                }
                public void onServiceConnected(ComponentName name, IBinder binder) {
                    serviceABinderInterface = (ServiceABinderInterface)binder;
                    int sum = serviceABinderInterface.sum(a, b);
                    Log.e(TAG, "onServiceConnected 1 sum = " + sum);
                    apkContext.showToast("sum = " + sum + "--" + serviceABinderInterface.hello(), Toast.LENGTH_SHORT);
                }
            };
            this.apkContext.bindService("com.example.plugina.ServiceA", serviceConnection, Context.BIND_AUTO_CREATE);
        }else{
            if (serviceABinderInterface != null){
                int sum = serviceABinderInterface.sum(a, b);
                Log.d(TAG, "onServiceConnected 2 sum = " + sum);
                apkContext.showToast("sum = " + sum + "--" + serviceABinderInterface.hello(), Toast.LENGTH_SHORT);
            }
        }
    }

    public void unbindService(){
        if (serviceConnection != null) {
            this.apkContext.unbindService("com.example.plugina.ServiceA", serviceConnection);
            serviceConnection = null;
        }
    }

    public void sayHello(Map<String, Object> params){
        Map<String, Object>unitInfo = new ArrayMap<>();
        unitInfo.put("name", "cetc28s");
        unitInfo.put("address", "北京路39号");
        String jsonStr = JsonFactory.getGson().toJson(unitInfo);
        Log.d(TAG, "unit info: " + jsonStr);

        String msg = "Hello from Man and hello from js name = " + params.get("name") + " and " + stringFromJNI();
        Log.d(TAG, msg);
        Map<String, Object>echoParams = new ArrayMap<>();
        echoParams.put("msg", msg);
        Log.d(TAG, "sayHello echo sayNativeHelloEcho");
        this.apkContext.post(new Runnable() {
            @Override
            public void run() {
                Man.this.apkContext.echo("sayNativeHelloEcho", echoParams);
            }
        });
    }

    public void startPicActivity(){
        String path = "%2f";
        Uri uri = Uri.parse("content://com.android.externalstorage.documents/document/primary:" + path);
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uri);

        this.apkContext.startActivityForResult(intent, testRequestCode, null);
    }
}
