package com.android.launcher3;

import android.Manifest;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.launcher3.accessibility.ListenerAppService;
import com.android.launcher3.manager.ColumnDef;
import com.android.launcher3.manager.LauncherManager;
import com.android.launcher3.manager.TimeModeManager;
import com.android.launcher3.model.ConfigManager;
import com.android.launcher3.model.TimeConfig;
import com.android.launcher3.util.Logger;
import com.android.launcher3.util.PermissionUtil;
import com.android.launcher3.util.TimeUtils;
import com.android.launcher3.views.SwipeUpFinishLayout;

import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Method;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;

/**
 * 锁屏
 */
public class LockScreenActivity extends BaseActivity implements View.OnClickListener {

    public static final String TAG = "LockScreenActivity";

    private TextView tvCurrentTime, tvCurrentDate;

    private TextView tVforceMode, tvRestMode, tvSwipeLock;

    private ConstraintLayout constraintRestMode, constraintNormalMode;

    private TextView tvNormalModeGameTime, tvNormalModeUseTime;

    private TextView tvRestModeResttime, tvRestModeUseTime;

    private ImageView ivCallPhone, ivMessage, ivCamera;

    private int lockMode;

    private SwipeUpFinishLayout swipeUpFinishLayout;

    private File imagePath;

    public static final int TIME_CYCLE = 1000;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            tvCurrentTime.setText(TimeUtils.getTime(System.currentTimeMillis(), TimeUtils.DATE_FORMAT_HH_MM));
            tvCurrentDate.setText(TimeUtils.getDate(System.currentTimeMillis(), TimeUtils.DATE_FORMAT_MM_dd));

            handler.sendEmptyMessageDelayed(0, TIME_CYCLE);
        }
    };

//    TYPE_APPLICATION_OVERLAY 获取不到焦点

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        View root = LayoutInflater.from(this).inflate(R.layout.activity_lock_screen, null);

        setContentView(root);


        hideStatusNavigationBar();

        findView(root);


        lockMode = LauncherManager.getInstance().getLockScreenMode();
        swipeUpFinishLayout = new SwipeUpFinishLayout(this);
        swipeUpFinishLayout.attachActivity(this);
        swipeUpFinishLayout.setEnable(false);
        switch (lockMode) {
            case ColumnDef.LockScreen.MODE_NORMAL:
                swipeUpFinishLayout.setEnable(true);
                setNormalModel();
                break;
            case ColumnDef.LockScreen.MODE_REST:
                setRestMode();
                break;
            case ColumnDef.LockScreen.MODE_FORCE_LOCK:
                setForceModel();
                break;

        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (lockMode != LauncherManager.getInstance().getLockScreenMode()) {
            lockMode = LauncherManager.getInstance().getLockScreenMode();

            switch (lockMode) {
                case ColumnDef.LockScreen.MODE_NORMAL:
                    setNormalModel();
                    break;
                case ColumnDef.LockScreen.MODE_REST:
                    setRestMode();
                    break;
                case ColumnDef.LockScreen.MODE_FORCE_LOCK:
                    setForceModel();
                    break;
            }
        }
    }

    private void findView(View root) {
        tvCurrentTime = root.findViewById(R.id.tv_current_time);
        tvCurrentDate = root.findViewById(R.id.tv_current_date);
        tVforceMode = root.findViewById(R.id.tv_force_mode);
        tvRestMode = root.findViewById(R.id.tv_rest_mode);
        constraintRestMode = root.findViewById(R.id.constraint_rest_mode);
        constraintNormalMode = root.findViewById(R.id.constraint_normal_mode);
        tvSwipeLock = root.findViewById(R.id.tv_swipe_lock);


        tvNormalModeGameTime = root.findViewById(R.id.tv_game_time);
        tvNormalModeUseTime = root.findViewById(R.id.tv_normal_mode_use_time);
        tvRestModeResttime = root.findViewById(R.id.tv_rest_time);
        tvRestModeUseTime = root.findViewById(R.id.tv_normal_use_time);
        ivMessage = root.findViewById(R.id.iv_message);
        ivCallPhone = root.findViewById(R.id.iv_call_phone);
        ivCamera = root.findViewById(R.id.iv_camera);


        ivCallPhone.setOnClickListener(this);
        ivMessage.setOnClickListener(this);
        ivCamera.setOnClickListener(this);

        tvCurrentTime.setText(TimeUtils.getTime(System.currentTimeMillis(), TimeUtils.DATE_FORMAT_HH_MM));

        tvCurrentDate.setText(TimeUtils.getDate(System.currentTimeMillis(), TimeUtils.DATE_FORMAT_MM_dd));

        handler.sendEmptyMessageDelayed(0, TIME_CYCLE);
    }


    private int getNavigationBarHeight() {
        Resources resources = getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0) {
            int height = resources.getDimensionPixelSize(resourceId);
            return height;
        }
        return 0;
    }

    private void hideStatusNavigationBar() {

        int uiFlags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
        getWindow().getDecorView().setSystemUiVisibility(uiFlags);

    }

    public void setRestMode() {

        tvRestMode.setVisibility(View.VISIBLE);
        tVforceMode.setVisibility(View.GONE);
        constraintRestMode.setVisibility(View.VISIBLE);

        tvSwipeLock.setVisibility(View.GONE);
        constraintNormalMode.setVisibility(View.GONE);

        TimeConfig config = TimeModeManager.getInstance(this).getTimeConfig(TimeModeManager.getInstance(this).getCurrentWorkModel());

        if (config != null) {
            Logger.e(TAG, JSON.toJSONString(config));
            tvRestModeResttime.setText(config.getRestTimeRegion());
            tvRestModeUseTime.setText(config.getUseTimeRegion());
        } else {
            Logger.e(TAG, "TimeConfig null");
        }


    }

    public void setNormalModel() {

        tvRestMode.setVisibility(View.GONE);
        tVforceMode.setVisibility(View.GONE);
        constraintRestMode.setVisibility(View.GONE);

        tvSwipeLock.setVisibility(View.VISIBLE);
        constraintNormalMode.setVisibility(View.VISIBLE);
        TimeConfig config = TimeModeManager.getInstance(this).getTimeConfig(TimeModeManager.getInstance(this).getCurrentWorkModel());

        if (config != null) {
            Logger.e(TAG, "setNormalModel\t" + JSON.toJSONString(config));
            tvNormalModeGameTime.setText((config.getGameUseTimestamp() / 60) + "分钟");
            tvNormalModeUseTime.setText(config.getUseTimeRegion());
        } else {
            Logger.e(TAG, "TimeConfig null");
        }
    }

    public void setForceModel() {

        tvRestMode.setVisibility(View.GONE);
        constraintRestMode.setVisibility(View.GONE);
        tvSwipeLock.setVisibility(View.GONE);
        constraintNormalMode.setVisibility(View.GONE);
        tVforceMode.setVisibility(View.VISIBLE);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Logger.e(TAG, "onKeyDown");
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (LauncherManager.getInstance().isForceLock()) {
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {


        if (v == ivCallPhone) {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            startActivity(intent);
        } else if (v == ivCamera) {
//            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED){
                Intent imageCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                String rootPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
                String name = "bzsh_" + System.currentTimeMillis() + ".png";
                imagePath = new File(rootPath + "/bzsh/", name);
                if (!imagePath.exists()) {
                    imagePath.getParentFile().mkdir();
                }
                Logger.e(TAG, imagePath.getAbsolutePath());
                imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imagePath));// 设置图片输出路径
                imageCaptureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); //
                startActivity(imageCaptureIntent);
            }else {
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},100);
            }

        } else if (v == ivMessage) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setType("vnd.android-dir/mms-sms");
            startActivity(intent);
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        ConfigManager.getInstance().setLockScreen(true);
    }

    @Override
    protected void onResume() {

        super.onResume();
    }

    @Override
    protected void onPause() {
        ConfigManager.getInstance().setLockScreen(false);
        super.onPause();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (imagePath!=null){
            try {
                MediaStore.Images.Media.insertImage(getContentResolver(), imagePath.getAbsolutePath(), imagePath.getName(), null);//图片插入到系统图库
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + imagePath.getAbsolutePath())));//通知图库刷新

            imagePath=null;
        }

    }


    @Override
    protected void onDestroy() {
        handler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }
}
