package com.gnhz.clinic.eitc_erm_app.sightGlass;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.PixelCopy;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.content.res.AppCompatResources;

import com.github.chrisbanes.photoview.PhotoView;
import com.gnhz.clinic.eitc_erm_app.BuildConfig;
import com.gnhz.clinic.eitc_erm_app.MainActivity;
import com.gnhz.clinic.eitc_erm_app.R;

import java.util.Timer;
import java.util.TimerTask;

public class VideoSDK extends com.example.eitc_erm_app.sightGlass.BaseActivity {
    public Video videoDecoder;
    public SurfaceView mSurfaceView;
    private ProgressBar progressBar;
    private PhotoView clickView;
    private ImageView getImage;
    public Button deleteChecked;
    public Button checkAll;
    public Button cancelAll;
    private TextView textView;
    private ImageView restart;
    private Button recordButton;

    private DecodeUtil decodeUtil;
    private TextView sdkversion;
    private TextView devversion;
    private Button videobuttonStop;
    public static int fpsCount = 0;
    private Timer t = null;
    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                showButton();
            }
            if (msg.what == 2) {
                hideButton();
            }
            if (msg.what == 3) {
                hideProgress();
                if (videoDecoder != null && MyXUtil.h264PlayFlag) {
                    hideRestart();
//                    PopTip.show("打开视频成功！").iconSuccess();
                    Toast.makeText(VideoSDK.this, "打开视频成功！", Toast.LENGTH_SHORT).show();
                  /*  camera temp = camera.getInstance();
                    byte[] ver = new byte[32];
                    if (temp.getDevVersion(ver) == 0) {
                        //获取成功，例如：20200923_V10.8_sh999
                        devversion.setText(new String(ver).trim());
                    } else {
                        Log.e(TAG, "handleMessage: wtf,获取版本号失败！");
                    }
                    textView.setText("::" + MyXUtil.nowPort);*/
                    if (!MyXUtil.ketThreadFlag) {
                        ThreadPoolHelper.executeTask(() -> videoDecoder.StartKeyScanThread());
                    }
                    videobuttonStop.setText("停止");
                    // videobuttonStop.setCompoundDrawables(ResourcesCompat.getDrawable(Resources.getSystem(), R.drawable.stop, null), null, null, null);
                    videobuttonStop.setCompoundDrawablesWithIntrinsicBounds(AppCompatResources.getDrawable(VideoSDK.this, R.drawable.stop), null, null, null);

                } else {
                    showRestart();
                    closeAllSocket();
                    // TastyToast.makeText(videoSdkTemp, "当前网络没有找到设备", TastyToast.LENGTH_SHORT, TastyToast.ERROR);
//                    PopTip.show("当前网路没有找到设备！").iconError();
                    Toast.makeText(VideoSDK.this, "当前网路没有找到设备！", Toast.LENGTH_SHORT).show();
                }
            }
            if (msg.what == 4) {
                screenshot(mSurfaceView, 1920, 1080);
                Log.e("iMVR", "============msg.what==4=================");
            }
            if (msg.what == 5) {
                hideRestart();
                showProgress();
                ThreadPoolHelper.executeTask(() -> {
                    Log.e(TAG, "onCreate: 开始视频。。。。。");
                    videoDecoder.startVideoDecode();
                });
            }
            if (msg.what == 6) {
//                PopTip.show("已经存在视屏流！").iconError();
                Toast.makeText(VideoSDK.this, "已经存在视屏流！", Toast.LENGTH_SHORT).show();
            }
            if (msg.what == 7) {
                //发送心跳包失败
                startOrStopVideo();
            }
            if (msg.what == 8) {
                //wtf?
            }
            if (msg.what == 9) {
                // TastyToast.makeText(videoSdkTemp, "socket连接失败!", TastyToast.LENGTH_SHORT, TastyToast.ERROR);
//                PopTip.show("当前网络查找视频失败！").iconError();
                Toast.makeText(VideoSDK.this, "当前网络查找视频失败！", Toast.LENGTH_SHORT).show();
            }
            if (msg.what == 20) {
//                PopTip.show("←👈👈👈按键左").iconSuccess();
                Toast.makeText(VideoSDK.this, "按键左！", Toast.LENGTH_SHORT).show();
            }
            if (msg.what == 21) {
//                PopTip.show("按键右👉👉👉→").iconSuccess();
                Toast.makeText(VideoSDK.this, "按键右！", Toast.LENGTH_SHORT).show();
            }
            if (msg.what == 22) {
//                PopTip.show("按键下👇👇👇↓").iconSuccess();
                Toast.makeText(VideoSDK.this, "按键下！", Toast.LENGTH_SHORT).show();
            }
            if (msg.what == 23) {
//                PopTip.show("重置为AP模式，并自动关机！(*Φ皿Φ*)").iconSuccess();
                Toast.makeText(VideoSDK.this, "重置为AP模式，并自动关机！", Toast.LENGTH_SHORT).show();
            }
            if (msg.what == 24) {
                //  sdkversion.setText("Ver::" + BuildConfig.VERSION_NAME + BuildConfig.VERSION_CODE);
                sdkversion.setText("FPS : " + fpsCount);
                fpsCount = 0;
            }
            return false;
        }
    });


    @SuppressLint("SetTextI18n")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.videosdk_activity);
        initFindID();
        hideButton();
        initSurface();
        showProgress();
        sdkversion.setText("Ver::" + BuildConfig.VERSION_NAME + BuildConfig.VERSION_CODE);
//        TcpSender.SetDeviceType(0);
        calcuteFPS();
    }

    private void calcuteFPS() {
        if (t == null) {
            t = new Timer();
        }
        t.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                // System.out.println("hello world");
                // Log.e(TAG, "run: " + fpsCount);
                if (MyXUtil.h264PlayFlag) {
                    handler.sendEmptyMessage(24);
                }
            }
        }, 100, 1000);
    }


    Bitmap mScreenBitmap = null;

    public void screenshot(SurfaceView view, int outWidth, int outHeight) {
        mScreenBitmap = Bitmap.createBitmap(outWidth, outHeight, Bitmap.Config.ARGB_8888);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            PixelCopy.request(view, mScreenBitmap, new PixelCopy.OnPixelCopyFinishedListener() {
                @Override
                public void onPixelCopyFinished(int copyResult) {
                    if (PixelCopy.SUCCESS == copyResult) {
                        //获取成功
                        getImage.setImageBitmap(mScreenBitmap);
                    } else {
//                        PopTip.show("copy error,抓拍失败！").iconError();
                        Toast.makeText(VideoSDK.this, "copy error,抓拍失败！", Toast.LENGTH_SHORT).show();
                    }
                }
            }, handler);
        } else {
//            PopTip.show("安卓版本太低，抓拍失败！").iconWarning();
            Toast.makeText(VideoSDK.this, "安卓版本太低，抓拍失败！", Toast.LENGTH_SHORT).show();
        }
    }


    class MyClickListenner implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.checkAll) {

            }
            if (v.getId() == R.id.cancelAll) {

            }
            if (v.getId() == R.id.deleteChecked) {

            }
            if (v.getId() == R.id.face_recordbtn) {
                //record
                if (decodeUtil != null) {
                    if (!DecodeUtil.recordMp4Flag) {
                        decodeUtil.initRecordMp4(MyXUtil.getSdPath() + "test.mp4", 1920, 1080);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                recordButton.setText("recording.....");
                            }
                        });
                    } else {
                        decodeUtil.stopRecordMp4();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                recordButton.setText("record");
                            }
                        });
                    }
                }
            }

            if (v.getId() == R.id.toMain) {
                closeAllSocket();
                startActivity(new Intent(VideoSDK.this, MainActivity.class));
                finish();
            }
            if (v.getId() == R.id.clickView) {
                clickView.setImageDrawable(null);
                clickView.setVisibility(View.GONE);
            }

            if (v.getId() == R.id.restart) {
                if (videoDecoder == null) {
                    if (decodeUtil == null) {
                        decodeUtil = new DecodeUtil(mSurfaceView.getHolder().getSurface());
                        decodeUtil.StartCodec();
                    }
                    videoDecoder = new Video(handler, decodeUtil);
                    handler.sendEmptyMessage(5);
                } else {
                    handler.sendEmptyMessage(5);
                }
            }

            if (v.getId() == R.id.face_stopbtn) {
                startOrStopVideo();
            }
            if (v.getId() == R.id.face_capturebtn) {
                //手动抓图
                // Video.captureStill = true;
                handler.sendEmptyMessage(4);
            }
            if (v.getId() == R.id.getImage) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (clickView.getVisibility() != View.VISIBLE) {
                            clickView.setVisibility(View.VISIBLE);
                            clickView.setImageDrawable(getImage.getDrawable());
                        } else {
                            clickView.setImageDrawable(null);
                            clickView.setVisibility(View.GONE);
                        }
                    }
                });
            }
        }
    }

    private void startOrStopVideo() {
        if (MyXUtil.h264PlayFlag) {
            MyXUtil.h264PlayFlag = false;
            if (videoDecoder != null) {
                closeAllSocket();
                showRestart();
                Log.e(TAG, "onCreate: 停止解码");
            }
        } else {
            if (videoDecoder == null) {
                if (decodeUtil == null) {
                    decodeUtil = new DecodeUtil(mSurfaceView.getHolder().getSurface());
                    decodeUtil.StartCodec();
                }
                videoDecoder = new Video(handler, decodeUtil);
                handler.sendEmptyMessage(5);
            } else {
                handler.sendEmptyMessage(5);
            }
        }
    }


    private void closeAllSocket() {
        MyXUtil.h264PlayFlag = false;
        if (videoDecoder != null) {
            videoDecoder.closeSocket();
        }
    }

    //初始化播放相关
    private void initSurface() {
        mSurfaceView.getHolder().addCallback(new SurfaceHolder.Callback2() {
            @Override
            public void surfaceRedrawNeeded(@NonNull SurfaceHolder holder) {

            }

            @Override
            public void surfaceCreated(@NonNull SurfaceHolder holder) {
                if (decodeUtil == null) {
                    decodeUtil = new DecodeUtil(holder.getSurface());
                }
                if (videoDecoder == null) {
                    videoDecoder = new Video(handler, decodeUtil);
                }
                decodeUtil.StartCodec();
                handler.sendEmptyMessage(5);
            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
                MyXUtil.h264PlayFlag = false;
                if (videoDecoder != null) {
                    closeAllSocket();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showRestart();
                        }
                    });
                    Log.e(TAG, "onCreate: 停止解码");
                }
                if (decodeUtil != null) {
                    decodeUtil.StopCodec();
                }
            }
        });
    }


    private void initFindID() {
        MyClickListenner myClickListenner = new MyClickListenner();
        mSurfaceView = findViewById(R.id.surfaceView1);
        mSurfaceView.setFocusable(true);
        mSurfaceView.setFocusableInTouchMode(true);
        Button videobuttonCapture = findViewById(R.id.face_capturebtn);
        videobuttonCapture.setOnClickListener(myClickListenner);
        ImageButton toMain = findViewById(R.id.toMain);
        toMain.setOnClickListener(myClickListenner);
        videobuttonStop = findViewById(R.id.face_stopbtn);
        videobuttonStop.setOnClickListener(myClickListenner);
        textView = findViewById(R.id.showByteArr);
        clickView = findViewById(R.id.clickView);
        clickView.setOnClickListener(myClickListenner);
        progressBar = findViewById(R.id.progressStartVideo);
        deleteChecked = findViewById(R.id.deleteChecked);
        deleteChecked.setOnClickListener(myClickListenner);
        checkAll = findViewById(R.id.checkAll);
        checkAll.setOnClickListener(myClickListenner);
        cancelAll = findViewById(R.id.cancelAll);
        cancelAll.setOnClickListener(myClickListenner);
        restart = findViewById(R.id.restart);
        restart.setOnClickListener(myClickListenner);
        getImage = findViewById(R.id.getImage);
        getImage.setOnClickListener(myClickListenner);
        recordButton = findViewById(R.id.face_recordbtn);
        recordButton.setOnClickListener(myClickListenner);
        sdkversion = findViewById(R.id.sdkversion);
        devversion = findViewById(R.id.devversion);
        hideRestart();
    }

    private void showRestart() {
        restart.setVisibility(View.VISIBLE);
        videobuttonStop.setText("开启");
        videobuttonStop.setCompoundDrawablesWithIntrinsicBounds(AppCompatResources.getDrawable(this, R.drawable.start_video), null, null, null);
    }

    private void hideRestart() {
        restart.setVisibility(View.INVISIBLE);
    }

    private void showProgress() {
        progressBar.setVisibility(View.VISIBLE);
    }

    private void hideProgress() {
        progressBar.setVisibility(View.INVISIBLE);
    }

    private void showButton() {
        cancelAll.setVisibility(View.VISIBLE);
        checkAll.setVisibility(View.VISIBLE);
        deleteChecked.setVisibility(View.VISIBLE);
    }

    private void hideButton() {
        cancelAll.setVisibility(View.INVISIBLE);
        checkAll.setVisibility(View.INVISIBLE);
        deleteChecked.setVisibility(View.INVISIBLE);
    }

    //在大于23的android版本中,文件读写需要动态申请权限
    private void verifyStoragePermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if ((this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) || (this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
                this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            } else {
                Log.d(TAG, "已有权限,不需要再申请");
                // mHandler.sendEmptyMessage(MyHandler.PERMISSION_ALLOW);
            }
        } else {
            //  mHandler.sendEmptyMessage(MyHandler.PERMISSION_ALLOW);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0x01:  //动态申请的读写权限
                if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    //  mHandler.sendEmptyMessage(PERMISSION_ALLOW);
                } else {
                    //  Toast.makeText(this, "用户没有同意文件读取权限!", Toast.LENGTH_LONG).show();
//                    PopTip.show("用户没有同意文件读取权限").iconError();
                    Toast.makeText(VideoSDK.this, "用户没有同意文件读取权限！", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onUserLeaveHint() {
        //运用放到了后台
        super.onUserLeaveHint();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            closeAllSocket();
            Intent intent = new Intent();
            intent.setClass(VideoSDK.this, MainActivity.class);
            startActivity(intent);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        Log.e(TAG, "onResume: ------");
        super.onResume();
     /*   if (restart.getVisibility() == View.VISIBLE) {
            if (!MyXUtil.h264PlayFlag) {
                Log.e(TAG, "onResume: 重新回到界面，尝试重新开启视频********");
                handler.sendEmptyMessage(5);
            }
        }*/
    }

    @Override
    protected void onDestroy() {
        closeAllSocket();
        if (videoDecoder != null) {
            videoDecoder = null;
        }
        if (decodeUtil != null) {
            decodeUtil.StopCodec();
            decodeUtil = null;
        }
        MyXUtil.ketThreadFlag = false;
        ServerSocketUtil.closeServerSocket();
        if (t != null) {
            t.cancel();
        }
        super.onDestroy();
    }
}