package com.ads.cal.picturetranslate.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ExperimentalGetImage;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;

import com.ads.cal.core.InitClean;
import com.ads.cal.core.data.JumpInfo;
import com.ads.cal.core.manager.AppDataMgr;
import com.ads.cal.core.manager.AppMgr;
import com.ads.cal.core.utils.FragmentXUtils;
import com.ads.cal.core.views.fragments.HomeFragment;
import com.ads.cal.picturetranslate.LogUtils;
import com.ads.cal.picturetranslate.PermissionUtil;
import com.ads.cal.picturetranslate.PictureApplication;
import com.ads.cal.picturetranslate.R;
import com.ads.cal.picturetranslate.SharedPreferencesUtil;
import com.ads.cal.picturetranslate.Util;
import com.ads.cal.picturetranslate.base.BaseActivity;
import com.android.gem.core.Event;
import com.android.gem.core.Node;
import com.gem.media.InitA;
import com.gem.media.ad.AdManager;
import com.gem.media.ad.NativeAdClearManager;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.PkgUtils;
import com.google.common.util.concurrent.ListenableFuture;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;


@ExperimentalGetImage public class CameraActivity extends BaseActivity implements ImageAnalysis.Analyzer {

    private static final int SELECT_TAKE_PHONE = 1;
    private ImageCapture imageCapture;
    private ImageView imageView, selectPhone;
    private PreviewView mPreview;

    private HomeFragment homeFragment;
    private Node node;
    private long currentTime;

    private void init() {
        Intent intent = getIntent();
        if (intent != null) {
            boolean isCleanJunk = false;
            try {
                Messenger messenger = intent.getParcelableExtra("messenger");
                InitA.getInstance().setCleanMessenger(messenger);
            } catch (Exception e) {

            }
            try {
                node = intent.getParcelableExtra("node");
            } catch (Exception e) {
                //
            }
            String viewType = intent.getStringExtra("cleanViewType");
            report(Constants.NODE_CLEAR_PAGE_SHOW, TextUtils.isEmpty(viewType) ? "home" : viewType);
            try {
                String adData = intent.getStringExtra("adData");
                if (!TextUtils.isEmpty(adData)) {
                    try {
                        JSONArray array = new JSONArray(adData);
//                        AdManager.getInstance().setData(array, AdManager.CLEAR_TYPE);
                        AdManager.getInstance().setData(array, AdManager.CLEAR_TYPE);
                    } catch (Exception e) {
                        //
                    }
                }
            } catch (Exception e) {
                //
            }
            try {
                isCleanJunk = intent.getBooleanExtra("clearType", true);
                InitClean.INSTANCE.setCurrShowGarbage(isCleanJunk);
            } catch (Exception e) {

            }
            try {
                String running3rdApp = intent.getStringExtra("running3rdApp");
                if (!TextUtils.isEmpty(running3rdApp)) {
                    AppMgr.INSTANCE.updateRunning3rdApp(running3rdApp);
                }
            } catch (Exception e) {
                //
            }
            try {
                boolean notifySwitch = intent.getBooleanExtra("notifySwitch", false);
                boolean popSwitch = intent.getBooleanExtra("popSwitch", false);
                boolean permanentSwitch = intent.getBooleanExtra("permanentSwitch", false);
                AppDataMgr.INSTANCE.setVisibleReminderValue(permanentSwitch, popSwitch, notifySwitch);
            } catch (Exception e) {
                //
            }
            boolean toAnimPage = false;
            try {
                toAnimPage = intent.getBooleanExtra("toAnimPage", false);
                if (toAnimPage) {
                    PictureTranslateShowPhotoActivity.startPictureTranslateShowPhotoActivity(this, new JumpInfo(), isCleanJunk ? JumpInfo.JUMP_ACTIVITY_CLEAN_SCAN
                            : JumpInfo.JUMP_ACTIVITY_PROCESS_SCAN);
                }
            } catch (Exception e) {
                //
            }
            try {
                report("toAnimPage", String.valueOf(toAnimPage));
            } catch (Exception e) {
                //
            }
        }
        try {
            homeFragment = new HomeFragment();
            FragmentXUtils.add(getSupportFragmentManager(), homeFragment, android.R.id.content);
        } catch (Exception e) {
            finish();
        }
    }

    private void report(String type, String reason) {
        Event event = new Event();
        event.type = type;
        event.reason = reason;
        addNodeEvent(event);
    }

    private void addNodeEvent(Event event) {
        if (node != null) {
            try {
                String pkgName = PictureApplication.getApplication().getPackageName();
                JSONObject reason = new JSONObject();
                reason.put(Constants.MEDIA_PKG, pkgName);
                reason.put(Constants.REASON, event.reason);
                reason.put("vn", PkgUtils.getAppVersionName(PictureApplication.getApplication(), pkgName));
                reason.put("vc", PkgUtils.getAppVersionCode(PictureApplication.getApplication(), pkgName));
                event.reason = reason.toString();
            } catch (Exception e) {
            }
            node.addEvent(event);
        }
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (init == 0) {
            init();
            return;
        }
        // 隐藏状态栏和虚拟导航栏
        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN
        );

        // 隐藏虚拟导航栏
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        );

        setContentView(R.layout.activity_camera);
        initView();
        initData();
        try {
            initCamera();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.e("AAAAAAA", e.getMessage());
        }
        SharedPreferencesUtil.saveString(this, SharedPreferencesUtil.KEY_FIRST_CLK_TAKE_PHOTO, "clk");
    }


    private FrameLayout frameLayout;
    private String adPosition;
    @Override
    protected void onStop() {
        super.onStop();
        if (homeFragment != null) {
            adPosition = homeFragment.getMAdPosition();
            frameLayout = homeFragment.getNativeGroupView();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        currentTime = System.currentTimeMillis();
    }

    @Override
    public void onBackPressed() {
        if (homeFragment != null) {
            adPosition = homeFragment.getMAdPosition();
            frameLayout = homeFragment.getNativeGroupView();
            homeFragment.onBackPressed();
            homeFragment = null;
            return;
        }
        super.onBackPressed();
    }


    @Override
    protected void onDestroy() {
        InitA.getInstance().setAdShownCallback(null);
        InitA.getInstance().setAdNativeShownCallback(null);

        if (null != frameLayout) {
            frameLayout.removeAllViews();
        }
        if (!TextUtils.isEmpty(adPosition)) {
            NativeAdClearManager manager = AdManager.getInstance().getNativeManager(adPosition);
            manager.destroyAd();
        }
        Messenger messenger = InitA.getInstance().getCleanMessenger();
        if (null != messenger) {
            try {
                try {
                    report(Constants.NODE_CLEAR_PAGE_SHOW_TIME, String.valueOf(System.currentTimeMillis() - currentTime));
                } catch (Exception e){
                    //
                }
                Message message = Message.obtain();
                Bundle bundle = new Bundle();
                if (node != null) {
                    bundle.putParcelable("node", node);
                }
                message.setData(bundle);
                message.what = 5003;
                messenger.send(message);
            } catch (RemoteException e) {
                //
            }
        }
        super.onDestroy();
    }

    private void initView() {
        ImageView close = findViewById(R.id.close);
        close.setOnClickListener(v -> finish());
        mPreview = findViewById(R.id.preview);
        imageView = findViewById(R.id.take_photo);
        imageView.setOnClickListener(v -> startTakePhone());
        selectPhone = findViewById(R.id.select_phone);
        selectPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionUtil.checkSelfIMAGEPermission(CameraActivity.this, SELECT_TAKE_PHONE);
            }
        });
    }

    private void initData() {
        Uri firstImageUri = Util.getFirstImageUriFromGallery(this);
        if (firstImageUri == null) {
            return;
        }
        selectPhone.setImageURI(firstImageUri);

    }

    private void initCamera() {
        // 将Camera的生命周期和Activity绑定在一起（设定生命周期所有者），这样就不用手动控制相机的启动和关闭。
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this);
        cameraProviderFuture.addListener(() -> {
            ProcessCameraProvider processCameraProvider = null;
            try {
                processCameraProvider = cameraProviderFuture.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
            Preview preview = new Preview.Builder().build();
            preview.setSurfaceProvider(mPreview.getSurfaceProvider());
            // 创建拍照所需的实例
            imageCapture = new ImageCapture.Builder()
                    .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
                    .setJpegQuality(80).build();
            ImageAnalysis imageAnalysis = new ImageAnalysis.Builder().build();
            // Select back camera as a default
            CameraSelector cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;
            try {
                if (null == processCameraProvider) {
                    return;
                }
                processCameraProvider.unbindAll();
                processCameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture, imageAnalysis);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }, ContextCompat.getMainExecutor(this));
    }

    private void startTakePhone() {
        ImageCapture imageCapture = this.imageCapture;
        if (imageCapture == null) {
            return;
        }
        File photoFile = new File(getCacheDir(), "/" + System.currentTimeMillis() + ".jpeg");


        // 创建 output option 对象，用以指定照片的输出方式
        ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions
                .Builder(photoFile)
                .build();

        imageView.setEnabled(false);
        // 执行takePicture（拍照）方法
        imageCapture.takePicture(outputFileOptions,
                ContextCompat.getMainExecutor(this),
                new ImageCapture.OnImageSavedCallback() {// 保存照片时的回调
                    @Override
                    public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                        PictureTranslateShowPhotoActivity.startPictureTranslateShowPhotoActivity(CameraActivity.this, Uri.fromFile(photoFile));
                        imageView.setEnabled(true);
                    }

                    @Override
                    public void onError(@NonNull ImageCaptureException exception) {
                        LogUtils.e("AAAAAA", exception.getMessage());
                        imageView.setEnabled(true);
                    }
                });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == SELECT_TAKE_PHONE) {
            if (allPermissionsGranted(grantResults)) {
                PermissionUtil.toSystemPhoto(this, SELECT_TAKE_PHONE);
            } else {
                Toast.makeText(this, getString(R.string.app_toast_enable_permissions), Toast.LENGTH_SHORT).show();
            }
        }
    }

    private boolean allPermissionsGranted(int[] grantResults) {
        return grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 获取图片回调
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            if (requestCode == SELECT_TAKE_PHONE) {
                Uri selectedImageUri = data.getData();
                PictureTranslateShowPhotoActivity.startPictureTranslateShowPhotoActivity(CameraActivity.this, selectedImageUri);
            } else {
                PictureTranslateShowPhotoActivity.startPictureTranslateShowPhotoActivity(CameraActivity.this, data.getData());
                LogUtils.e("uri", data.getData().toString());
            }
        }
    }



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

    @Override
    public void analyze(@NonNull ImageProxy image) {
        LogUtils.e("AAAAAA", image.toString());
    }

    public static void startCameraActivity(Context context) {
        Intent intent = new Intent(context, CameraActivity.class);
        context.startActivity(intent);
    }
}
