package com.file.clean.q.view;

import static com.file.clean.q.GlobalConfig.URL_PRIVACY;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.file.clean.q.business.admob.AdmobManager;
import com.file.clean.q.business.newAdmob.AdmobHelps;
import com.file.clean.q.databinding.DialogMalwareBinding;
import com.file.clean.q.model.util.PermissionUtils;
import com.file.clean.q.util.NetWork;
import com.file.clean.q.view.activity.AnimatorActivity;
import com.file.clean.q.view.activity.MalwareCleanActivity;
import com.file.clean.q.view.activity.SimilarPhotosActivity;
import com.file.clean.q.view.dialog.CustomBottomSheetDialog;
import com.file.clean.q.view.dialog.FullscreenDialog;
import com.file.clean.q.view.weather.ListBean;
import com.file.clean.q.view.weather.WeatherBean;
import com.file.clean.q.view.weather.WeatherInterface;
import com.file.clean.q.view.weather.WeatherUtils;
import com.gyf.immersionbar.ImmersionBar;

import com.file.clean.q.model.tool.MemoryUtils;
import com.file.clean.q.view.activity.CleanJunkActivity;
import com.file.clean.q.view.activity.InfoActivity;
import com.file.clean.q.view.activity.LargeFileActivity;
import com.file.clean.q.view.activity.ScreenShotActivity;
import com.file.clean.q.view.activity.SettingActivity;

import com.file.clean.q.view.dialog.AppExitDialog;
import com.file.clean.q.view.dialog.NoticeDialog;
import com.file.clean.q.R;
import com.file.clean.q.databinding.ActivityMainBinding;
import com.link.play.ad.LinkPlaySdk;

import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;
    private ObjectAnimator rotateAnimator;
    private FullscreenDialog fullscreenDialog;
    private ActivityResultLauncher<String[]> multiplePermissionsLauncher;
    private ActivityResultLauncher<Intent> notificationSettingsLauncher;
    private static final int REQUEST_CODE_STORAGE_PERMISSION = 101;
    private static final int REQUEST_ALL_FILES_ACCESS_PERMISSION = 100;
    private static final int REQUEST_PERMISSION_CODE = 102;
    private CustomBottomSheetDialog customBottomSheetDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);
        initBar();
        initDialog();
        initPermission();
        initShow();
        binding.cl3Bingdu.setOnClickListener(v -> {
            NetWork netWork = new NetWork();
            boolean networkAvailable = netWork.isNetworkAvailable(this);
            if (networkAvailable){
                showTipsDialog(this, () -> {
                    qx();
                });
            }else {
                Toast.makeText(this, this.getString(R.string.no_network_try), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initDialog() {
        if (!isCleaned()) {
            fullscreenDialog = new FullscreenDialog(this);
            fullscreenDialog.setOnDialogDismissListener(new FullscreenDialog.OnDialogDismissListener() {
                @Override
                public void onSuccButton() {
                    if (!checkFilesAccessPermission(MainActivity.this)) {
                        // 没有权限，请求权限
                        customBottomSheetDialog = new CustomBottomSheetDialog();
                        customBottomSheetDialog.setOnOpenSettingClickListener(new CustomBottomSheetDialog.OnOpenSettingClickListener() {
                            @Override
                            public void onOpenSettingClick(boolean isSwitchChecked) {
                                if (isSwitchChecked){
                                    requestFilesAccessPermission();
                                }else {
                                    Toast.makeText(MainActivity.this, "Please turn on the permission switch", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                        customBottomSheetDialog.show(getSupportFragmentManager(),"CustomBottomSheetDialog");
                    }else {
                        initStart();
                    }
                }
            });
            fullscreenDialog.show();
        }
    }

    private void qx() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 如果没有权限，请求权限
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, REQUEST_CODE_STORAGE_PERMISSION);
        } else {
            // 如果已经有权限，执行相关操作
            performPermissionGrantedAction();
        }
    }
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_CODE_STORAGE_PERMISSION) {
            if (grantResults.length > 0 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED &&
                    grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                // 用户授予了权限
                performPermissionGrantedAction();
            } else {
                // 用户拒绝了权限
                performPermissionGrantedAction();
            }
        }
        if (requestCode == REQUEST_ALL_FILES_ACCESS_PERMISSION || requestCode == REQUEST_PERMISSION_CODE) {
            if (!checkFilesAccessPermission(this)) {
                // 权限未授予，直接关闭页面
                Toast.makeText(this, "Unauthorized permission, the page is about to close", Toast.LENGTH_SHORT).show();
                fullscreenDialog.dismiss();
                customBottomSheetDialog.dismiss();
            }
        }

    }
    public void showTipsDialog(Context context, final Runnable confirm) {
        if (!isCleanedBingDu()) {
            DialogMalwareBinding binding = DialogMalwareBinding.inflate(LayoutInflater.from(context));
            Dialog dialog = new Dialog(context,R.style.TransparentDialogTheme);
            //dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCanceledOnTouchOutside(true);
            dialog.setCancelable(true);
            dialog.setContentView(binding.getRoot());
            dialog.show();

            binding.tvCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            SharedPreferences prefs = getSharedPreferences("CleanBingDu", MODE_PRIVATE);
            binding.tvSure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SharedPreferences.Editor edit = prefs.edit();
                    edit.putBoolean("cleanbd",true);
                    edit.commit();
                    v.setEnabled(false);
                    dialog.dismiss();
                    confirm.run();
                }
            });

            binding.tvContent8.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    context.startActivity(
                            new Intent(Intent.ACTION_VIEW, Uri.parse(context.getString(R.string.trustlook_privacy_policy)))
                    );
                }
            });

            binding.tvContent8.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

            binding.tvContent10.setText(URL_PRIVACY);
            binding.tvContent10.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    context.startActivity(
                            new Intent(Intent.ACTION_VIEW, Uri.parse(URL_PRIVACY))
                    );
                }
            });

            binding.tvContent10.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        } else {
            confirm.run();
        }
    }

    private void initShow() {
        //判断是否有权限
//        NotificationUtils.INSTANCE.sendNotification(CleanApplication.context, GlobalConfig.ID_CLEAN_JUNK, "app_receiver");
        //动画
        initAnimate();
        initWheather();
        new Thread(){
            @Override
            public void run() {
                super.run();
                // 获取总内存
                String totalMemory = MemoryUtils.getUsedDiskMemory(MainActivity.this);
                // 获取当前使用内存
                String usedMemory = MemoryUtils.getTotalDiskMemory(MainActivity.this);
                String usedDiskMemoryPercent = MemoryUtils.getUsedDiskMemoryPercent(MainActivity.this);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //内存赋值
                        binding.phoneMemory.setText(totalMemory + "/" + usedMemory);
                        binding.tvBaifenbi.setText(usedDiskMemoryPercent);
                        binding.progressBar.setProgress(Integer.parseInt(usedDiskMemoryPercent));
                    }
                });
            }
        }.start();
        binding.cleanUp.setOnClickListener(v -> {
            initStart();
        });
        binding.ivSetting.setOnClickListener(v -> {
            initSetting();
        });
        binding.cl3CleanJunk.setOnClickListener(v -> {
            initStart();
        });
        binding.cl3BatteryInfo.setOnClickListener(v -> {
            Intent intent = new Intent(this, AnimatorActivity.class);
            intent.putExtra("animator",2);
            startActivity(intent);
        });
        binding.largeFileCleaner.setOnClickListener(v -> {
            Intent intent = new Intent(this, AnimatorActivity.class);
            intent.putExtra("animator",3);
            startActivity(intent);
        });
        binding.screenshotCleaner.setOnClickListener(v -> {
            Intent intent = new Intent(this, AnimatorActivity.class);
            intent.putExtra("animator",4);
            startActivity(intent);
        });
        binding.similarPhotos.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, SimilarPhotosActivity.class));
        });
        binding.clTianqi.setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, WeatherInterface.class));
        });
    }
    private void initWheather() {
        WeatherBean weatherEntity = WeatherUtils.INSTANCE.getWeatherEntity();
        if (weatherEntity!= null &&!weatherEntity.getList().isEmpty()) {
            ListBean bean = weatherEntity.getList().get(0);
            int value = 22;
            int min = Integer.parseInt(bean.getTempMin());
            int max = Integer.parseInt(bean.getTempMax());

            if (min == max) {
                value = max;
            } else if (min < max) {
                Random random = new Random();
                value = random.nextInt(max - min) + min;
            }

            int icon;
            String weatherType = WeatherUtils.INSTANCE.getWeatherType(Integer.parseInt(bean.getIconDay()));
            switch (weatherType) {
                case "Sunny day":
                    icon = R.mipmap.x_qing;
                    break;
                case "Cloudy day":
                    icon = R.mipmap.x_yin;
                    break;
                case "Rainy day":
                    icon = R.mipmap.x_dayu;
                    break;
                case "Snowy day":
                    icon = R.mipmap.x_xiaxue;
                    break;
                case "Greasy day":
                    icon = R.mipmap.x_wumaishachengbao;
                    break;
                case "Unknown":
                    icon = R.mipmap.x_qing;
                    break;
                default:
                    icon = R.mipmap.x_qing;
                    break;
            }

            binding.clTianqiSize.setText(String.valueOf(value));
            binding.clTianqiImg.setImageResource(icon);
        }else {
            binding.clTianqiSize.setText("");
            binding.clTianqiImg.setImageResource(R.mipmap.duoyun);
        }
    }

    private void initAnimate() {
        rotateAnimator = ObjectAnimator.ofFloat(binding.animateYuan, "rotation", 360f, 0f);
        rotateAnimator.setDuration(5000);

        rotateAnimator.setRepeatMode(ObjectAnimator.RESTART);
        rotateAnimator.setRepeatCount(ObjectAnimator.INFINITE);
        rotateAnimator.start();


        int width = getResources().getDimensionPixelSize(R.dimen.main_progress_bar_width); // 宽度
        int height = getResources().getDimensionPixelSize(R.dimen.main_progress_bar_height);
        binding.progressBar.getLayoutParams().width = width;
        binding.progressBar.getLayoutParams().height = height;
        binding.progressBar.requestLayout();
    }
    private boolean isCleaned() {
        SharedPreferences prefs = getSharedPreferences("AppPrefs", MODE_PRIVATE);
        return prefs.getBoolean("cleaned", false);
    }
    private boolean isCleanedBingDu() {
        SharedPreferences prefs = getSharedPreferences("CleanBingDu", MODE_PRIVATE);
        return prefs.getBoolean("cleanbd", false);
    }
    private void initPermission() {
        multiplePermissionsLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestMultiplePermissions(),
                result -> {
                    if (result.get(Manifest.permission.POST_NOTIFICATIONS) != null && result.get(Manifest.permission.POST_NOTIFICATIONS)) {

                    }
                }
        );


        notificationSettingsLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    // 处理结果
                }
        );
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                NoticeDialog noticeDialog = new NoticeDialog(this);
                noticeDialog.setOnDialogClickListener(new NoticeDialog.OnDialogClickListener() {
                    @Override
                    public void onCancel() {
                        noticeDialog.cancel();
                    }

                    @Override
                    public void onSubmit() {
                        // 请求通知权限
                        PermissionUtils.requestNotificationPermission(MainActivity.this, notificationSettingsLauncher, multiplePermissionsLauncher);
                        noticeDialog.cancel();

                    }
                });
                noticeDialog.show();
            }

        }



    }
    private boolean checkFilesAccessPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            return Environment.isExternalStorageManager();
        } else {
            int readPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
            int writePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            return readPermission == PackageManager.PERMISSION_GRANTED && writePermission == PackageManager.PERMISSION_GRANTED;
        }
    }

    private void requestFilesAccessPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            try {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.addCategory("android.intent.category.DEFAULT");
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_ALL_FILES_ACCESS_PERMISSION);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(this, "Unable to request permission, please grant manually", Toast.LENGTH_SHORT).show();
            }
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CODE);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ALL_FILES_ACCESS_PERMISSION) {
            // 检查权限是否已经授予
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    // 权限已授予，刷新页面或执行相关操作
                    initStart();
                    fullscreenDialog.dismiss();
                    customBottomSheetDialog.dismiss();
                } else {
                    fullscreenDialog.dismiss();
                    customBottomSheetDialog.dismiss();
                    // 权限未授予，提示用户
                    Toast.makeText(this, "Permission not granted, please grant manually", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
    private void initSetting() {
        Intent intent = new Intent(this, SettingActivity.class);
        startActivity(intent);
    }
    private void initStart() {
        Intent intent = new Intent(this, AnimatorActivity.class);
        intent.putExtra("animator",1);
        startActivity(intent);
    }
    private void initBar() {
        ImmersionBar.with(this)
                .transparentStatusBar()  // 透明状态栏
                .statusBarDarkFont(false)  // 状态栏字体颜色为深色
                .navigationBarDarkIcon(true)  // 导航栏图标颜色为浅色
                .init();
    }
    private void performPermissionGrantedAction() {
        startActivity(new Intent(this, MalwareCleanActivity.class));
    }
    @Override
    public void onBackPressed() {
        AppExitDialog appExitDialog = new AppExitDialog(this);
        appExitDialog.setOnDialogClickListener(new AppExitDialog.OnDialogClickListener() {
            @Override
            public void onCancel() {
                appExitDialog.dismiss();
            }

            @Override
            public void onSubmit() {
                finishAffinity();
                System.exit(0); // 完全退出应用
            }
        });
        appExitDialog.show();
    }

    private AtomicBoolean bannerShowed = new AtomicBoolean(false);

    @Override
    protected void onResume() {
        super.onResume();
        LinkPlaySdk.showView(this);
        if (isCleaned() && fullscreenDialog != null) {
            Log.d("isCleaned", isCleaned() + "222");
            fullscreenDialog.dismiss();
            fullscreenDialog = null; // 释放引用
        }
        if (!rotateAnimator.isRunning()) {
            rotateAnimator.start();
        }
        AdmobHelps.INSTANCE.showNativeAd(this,binding.flAd,R.layout.layout_ad_native_small, AdmobHelps.INSTANCE.isShowAdNativeBottom(),false);
        if (bannerShowed.get()) return;
        bannerShowed.set(true);
        if (AdmobHelps.INSTANCE.isShowAdBanner()){
            AdmobHelps.INSTANCE.showBannerAd(this, binding.flBanner, "bottom", null, null);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (rotateAnimator.isRunning()) {
            rotateAnimator.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (rotateAnimator != null) {
            rotateAnimator.end();
            rotateAnimator = null;
        }

        if (fullscreenDialog!= null) {
            fullscreenDialog.dismiss();
            fullscreenDialog = null; // 释放引用
        }
    }
}