package com.hainaos.vc.activity.main;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.hainaos.vc.BuildConfig;
import com.hainaos.vc.R;
import com.hainaos.vc.activity.vip.VipActivity;
import com.hainaos.vc.base.BaseFragmentPagerAdapter;
import com.hainaos.vc.base.mvvm.BaseMvvmActivity;
import com.hainaos.vc.databinding.ActivityMainBinding;
import com.hainaos.vc.dialog.PermissionsDialog;
import com.hainaos.vc.fragment.pic.PictureFragment;
import com.hainaos.vc.fragment.video.VideoFragment;
import com.hainaos.vc.utils.JgyUtils;
import com.hainaos.vc.utils.ToastUtil;
import com.hainaos.vc.utils.VideoUtils;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import io.reactivex.rxjava3.annotations.NonNull;

public class MainActivity extends BaseMvvmActivity<MainViewModel, ActivityMainBinding> {
    private static final String TAG = "MainActivity";

    private static final int REQUEST_PERMISSION_CODE = 200;

    private String[] title = new String[]{"视频", "照片"};

    private BaseFragmentPagerAdapter mPagerAdapter;
    private FragmentManager mFragmentManager;
    private List<Fragment> mFragments;
    private PictureFragment mPictureFragment;
    private VideoFragment mVideoFragment;

    String[] permissions = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public boolean setNightMode() {
        return false;
    }

    @Override
    protected void initDataBinding() {
        mViewModel.setCtx(this);
        mViewModel.setVDBinding(mViewDataBinding);
        mViewModel.setLifecycle(getLifecycleSubject());
        mViewDataBinding.setClick(new Click());
    }

    @Override
    public void initView() {
        mViewDataBinding.tvVersion.setText("V" + BuildConfig.VERSION_NAME);
        mFragments = new ArrayList<>();
        if (mVideoFragment == null) {
            mVideoFragment = new VideoFragment();
        }
        if (mPictureFragment == null) {
            mPictureFragment = new PictureFragment();
        }
        mFragments.add(mVideoFragment);
        mFragments.add(mPictureFragment);
        mFragmentManager = getSupportFragmentManager();
        mPagerAdapter = new BaseFragmentPagerAdapter(mFragmentManager, mFragments);
        mViewDataBinding.viewPager.setAdapter(mPagerAdapter);
        mViewDataBinding.mainSlidingTabLayout.setViewPager(mViewDataBinding.viewPager, title);

    }

    @Override
    public void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        checkSelfPermission();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.e("TAG", "onRequestPermissionsResult: ");
                getThumbnail();
            } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    ToastUtil.show("需要存储空间权限才能正常使用软件");
                    checkSelfPermission();
                } else {
                    ToastUtil.show("请打开存储空间权限后使用软件");
                    Intent intent = new Intent();
                    intent.setAction(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(Uri.parse("package:" + this.getPackageName()));
                    startActivity(intent);
                }
            }
        }
    }

    private PermissionsDialog mPermissionsDialog;

    private void showPermissionsDialog() {
        if (mPermissionsDialog != null) {
            mPermissionsDialog.dismiss();
            mPermissionsDialog = null;
        }
        mPermissionsDialog = new PermissionsDialog(MainActivity.this);
        mPermissionsDialog.setPermissionsCallback(new PermissionsDialog.PermissionsCallback() {
            @Override
            public void onGranted() {
                mPermissionsDialog.dismiss();
                XXPermissions.with(MainActivity.this)
                        .permission(permissions)
                        .request(new OnPermissionCallback() {
                            @Override
                            public void onGranted(@androidx.annotation.NonNull List<String> permissions, boolean allGranted) {
                                Log.e(TAG, "onGranted: permissions = " + permissions + " allGranted = " + allGranted);
                                if (!allGranted) {
                                    Toast.makeText(MainActivity.this, "存储权限未正常授予", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                Log.e(TAG, "onGranted: 获取存储权限成功");
                            }

                            @Override
                            public void onDenied(@androidx.annotation.NonNull List<String> permissions, boolean doNotAskAgain) {
                                Log.e(TAG, "onDenied: permissions = " + permissions + " doNotAskAgain = " + doNotAskAgain);
                                if (doNotAskAgain) {
                                    Toast.makeText(MainActivity.this, "被永久拒绝授权，请手动授予存储权限", Toast.LENGTH_SHORT).show();
                                    // 如果是被永久拒绝就跳转到应用权限系统设置页面
                                    XXPermissions.startPermissionActivity(MainActivity.this, permissions);
                                } else {
                                    Log.e(TAG, "onGranted: 获取存储权限失败");
                                }
                            }
                        });
            }

            @Override
            public void onDenied() {
                mPermissionsDialog.dismiss();
            }
        });
        mPermissionsDialog.setContent("本软件需要获取存储权限保存照片和视频，授权之后才可以正常使用");
        mPermissionsDialog.show();
    }

    private void checkSelfPermission() {
        if (XXPermissions.isGranted(MainActivity.this, permissions)) {
        } else {
            showPermissionsDialog();
//                ActivityCompat.requestPermissions(this, permissions, REQUEST_PERMISSION_CODE);
            }
    }

    private void getThumbnail() {
        long s1 = System.currentTimeMillis();
        List<String> picFileList = new ArrayList<>();
        List<String> videoFileList = new ArrayList<>();
        String rootPath = JgyUtils.getInstance().getDownLoadPath() + File.separator;
        File file = new File(rootPath);
        if (file.exists()) {
            LinkedList<File> list = new LinkedList<File>();
            File[] files = file.listFiles();
            if (files == null) {
                return;
            }
            for (File file2 : files) {
                if (file2.isDirectory()) {
                    list.add(file2);
                } else {
                    if (VideoUtils.isPicFormat(file2.getAbsolutePath())) {
                        picFileList.add(file2.getAbsolutePath());
                    } else if (VideoUtils.isVideoFormat(file2.getAbsolutePath())) {
                        videoFileList.add(file2.getAbsolutePath());
                    }
                }
            }
            File temp_file;
            while (!list.isEmpty()) {
                temp_file = list.removeFirst();
                files = temp_file.listFiles();
                if (files == null) {
                    continue;
                }
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        list.add(file2);
                    } else {
                        if (VideoUtils.isPicFormat(file2.getAbsolutePath())) {
                            picFileList.add(file2.getAbsolutePath());
                        } else if (VideoUtils.isVideoFormat(file2.getAbsolutePath())) {
                            videoFileList.add(file2.getAbsolutePath());
                        }
                    }
                }
            }
        } else {
            Log.e("traverseFolder1", "文件不存在!");
        }
        Log.e("ScanTask", "doInBackground: " + "Scan time = " + (System.currentTimeMillis() - s1) + "ms");
        Log.e("getThumbnail", "picFileList: " + picFileList);
        Log.e("getThumbnail", "videoFileList: " + videoFileList);
        Log.e("getThumbnail", "picFileList size = " + picFileList.size());
        Log.e("getThumbnail", "videoFileList size = " + videoFileList.size());

        Log.e("getThumbnail", "videoFileList size = " + videoFileList.size());
    }


    /**
     * 将本地图片转换为 Drawable
     *
     * @param file 文件路径
     * @return
     */
    public Drawable path2Drawable(String file) {
        if (file == null || file.isEmpty()) {
            return null;
        }
        Drawable drawable = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            Bitmap bitmap = BitmapFactory.decodeStream(fis);
            drawable = new BitmapDrawable(getResources(), bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return drawable;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == KeyEvent.ACTION_DOWN) {
            lazyExit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private long mPreClickTime;

    private void lazyExit() {
        if (System.currentTimeMillis() - mPreClickTime > 3000) {
            ToastUtil.show("再按一次，退出");
            mPreClickTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

    public class Click {
        public void exit(View view) {
            lazyExit();
        }

        public void toVip(View view) {
            startActivity(new Intent(MainActivity.this, VipActivity.class));
        }
    }
}
