package com.ez.ertc;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.ez.baselib.utils.LogFileService;
import com.ez.whiteboard.mode.OpenModel;
import com.ez.whiteboard.view.DrawFrameLayout;
import com.gyf.immersionbar.ImmersionBar;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

/**
 * @author shenen.gao
 * @date 2023-4-26
 */
public class TestWhiteBoardActivity extends AppCompatActivity {

    private DrawFrameLayout drawFrameLayout;
    private View btnContainer;
    private View btnOpen;
    private View btnOpenPic;
    private View btnOpenPicSmall;
    private View btnClose;
    private TextView tvLog;

    private final List<String> logs = new ArrayList<>();

    private final Handler mainHandler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar.with(this).init();
        setContentView(R.layout.test_white_board_activiy);
        init();

        Pair<String, String> info = getUserName();
        ((EditText) findViewById(R.id.edit_user_id)).setText(info.first);
        ((EditText) findViewById(R.id.edit_room_id)).setText(info.second);
    }

    private void init() {
        btnContainer = findViewById(R.id.ll_btn_container);
        btnOpen = findViewById(R.id.btn_open);
        btnOpenPic = findViewById(R.id.btn_open_pic);
        btnClose = findViewById(R.id.btn_close);
        btnOpenPicSmall = findViewById(R.id.btn_open_pic_small);
        tvLog = findViewById(R.id.tv_log);

        btnOpen.setOnClickListener(v -> {
            btnContainer.setVisibility(View.GONE);
            btnClose.setVisibility(View.VISIBLE);
            tvLog.setVisibility(View.VISIBLE);
            open(null);
        });
        btnOpenPic.setOnClickListener(v -> {
            btnContainer.setVisibility(View.GONE);
            btnClose.setVisibility(View.VISIBLE);
            tvLog.setVisibility(View.VISIBLE);
            open(drawableToBitmap(ContextCompat.getDrawable(this, R.drawable.white_board_test_pic)));
        });
        btnOpenPicSmall.setOnClickListener(v -> {
//            btnContainer.setVisibility(View.GONE);
//            btnClose.setVisibility(View.VISIBLE);
//            tvLog.setVisibility(View.VISIBLE);
//            open(drawableToBitmap(ContextCompat.getDrawable(this, R.drawable.icon_mt_beauty_filter_baixi)));
            startActivityForResult(new Intent(Intent.ACTION_PICK).setType("image/*"),0);
        });
        btnClose.setOnClickListener(v -> {
            btnContainer.setVisibility(View.VISIBLE);
            btnClose.setVisibility(View.GONE);
            tvLog.setVisibility(View.GONE);
            close();
        });

        initWhiteBoard();
    }

    private void initWhiteBoard() {
        drawFrameLayout = findViewById(R.id.drawFrameLayout);
        drawFrameLayout.setFixedLandScape(true);
        drawFrameLayout.setDrawBackgroundResource(R.color.white);
        drawFrameLayout.setLogCallBack((level, tag, content) -> {
            if (level == 1) {
                Log.d(tag, content);
            } else if (level == 2) {
                Log.i(tag, content);
                filterLog(content);
                renderLog();
            } else if (level == 3) {
                Log.w(tag, content);
            } else if (level == 4) {
                Log.e(tag, content);
                filterLog(content);
                renderLog();
            }
        });
    }
    private void open(Bitmap pic) {
        hideSoftKeyboard(findViewById(R.id.edit_room_id));
        hideSoftKeyboard(findViewById(R.id.edit_user_id));

        String roomId = ((EditText) findViewById(R.id.edit_room_id)).getText().toString();
        String userName = ((EditText) findViewById(R.id.edit_user_id)).getText().toString();
        boolean isDebugLog = ((CheckBox) findViewById(R.id.check_box_log)).isChecked();
        boolean isTraceLog = ((CheckBox) findViewById(R.id.check_box_log_trace)).isChecked();

        // 是否内网
        boolean inNet = ((CheckBox) findViewById(R.id.check_box_line)).isChecked();
        saveUserName(userName, roomId);

        if (!roomId.isEmpty() && !userName.isEmpty()) {
            logs.clear();
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            drawFrameLayout.setVisibility(View.VISIBLE);

            OpenModel model = new OpenModel();

//            model.setAddress("test11.ys7.com");
            model.setAddress("10.86.15.202");
//            model.setAddress("10.86.15.209");

            model.setPort(8554);
            model.setPubKey("MFkwEwYHKoZIzj0CAQYIKo==================");
            model.setUserId(userName);
            model.setRoomId(roomId);
            model.setCustomRoomId(roomId);
            model.setAppId("at.bz3bgmna990fjqh173v4hvqb102bqevl-7awowq3xa8-0l6kjax-khjahgymu");
            model.setToken("token===================================");
            model.setLogLevel(isDebugLog ? OpenModel.LOG_LEVEL_DEBUG : OpenModel.LOG_LEVEL_INFO);
            if (isTraceLog) {
                model.setLogLevel(OpenModel.LOG_LEVEL_TRACE);
            }
            model.setPicture(pic);
            model.setLineId(inNet ? 2 : 1);

            String logPath = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getPath();
            Calendar calendar = Calendar.getInstance();
            String fileName = String.format(Locale.CHINA, "/white_board_log_%04d%02d%02d_%02d", calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY));
            LogFileService.start(logPath + fileName + ".txt");

            drawFrameLayout.start(model);
        }
    }

    private void close() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
        drawFrameLayout.setVisibility(View.GONE);
        drawFrameLayout.close();

        LogFileService.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        drawFrameLayout.close();
    }

    private Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    private void renderLog() {
        List<String> copyLogs = new ArrayList<>();
        copyLogs.addAll(logs);
        mainHandler.post(() -> {
            try {
                StringBuilder logStr = new StringBuilder();
                tvLog.setText("");
                for (String log : copyLogs) {
                    logStr.append(log + "\n");
                }
                tvLog.setText(logStr.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void filterLog(String log) {
        try {
            if (log.contains("[SVG]init")) {
                addLogToList("初始化成功");
            }
            if (log.contains("Join Local success")) {
                addLogToList("我加入");
            }
            if (log.contains("Exit room success")) {
                addLogToList("我离开");
            }
            if (log.contains("Join Remote user")) {
                log = log.substring(log.indexOf("er:") + 3) + "加入";
                addLogToList(log);
            }
            if (log.contains("Leave Remote user")) {
                log = log.substring(log.indexOf("er:") + 3) + "离开";
                addLogToList(log);
            }
            if (log.contains("[JNI][SIGN]network changed 1")) {
                addLogToList("网络异常重试中");
                addLogToList("加载中~");
            }
            if (log.contains("[JNI][SIGN]network changed 2")) {
                addLogToList("网络恢复");
            }
            if (log.contains("[JNI][SIGN]network changed 3")) {
                addLogToList("网络恢复");
            }
            if (log.contains("[JNI][SIGN]Error code: 2005  msg: reconnecting")) {
                addLogToList("连接中");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addLogToList(String str) {
        if (logs.isEmpty()) {
            logs.add(str);
        }
        if (!Objects.equals(logs.get(logs.size() - 1), str)) {
            if (logs.size() > 18) {
                logs.remove(0);
            }
            logs.add(str);
        }
    }

    /**
     * 隐藏软键盘(只适用于Activity，不适用于Fragment)
     */
    private void hideSoftKeyboard(View view) {
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private void saveUserName(String userName, String roomId) {
        SharedPreferences.Editor editor = getSharedPreferences("test_white_board", 0).edit();
        editor.putString("userName", userName);
        editor.putString("roomId", roomId);
        editor.commit();
    }

    private Pair<String, String> getUserName() {
        SharedPreferences preferences = getSharedPreferences("test_white_board", 0);
        String userName = preferences.getString("userName", "");
        if (userName.isEmpty()) {
            userName = "Android" + (int) (Math.random() * 1000);
        }
        String roomId = preferences.getString("roomId", "609596136");
        return new Pair<>(userName, roomId);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ContentResolver contentResolver = getContentResolver();
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(data.getData()));
            Log.i("TAG", "从相册回传bitmap："+bitmap);
            btnContainer.setVisibility(View.GONE);
            btnClose.setVisibility(View.VISIBLE);
            tvLog.setVisibility(View.VISIBLE);
            open(bitmap);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
