package com.android.launcher3.accessibility;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.launcher3.LockScreenInterface;
import com.android.launcher3.R;
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.TimeUtils;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

public class FloatWindowService extends Service implements View.OnClickListener {


    private static final String TAG = "FloatWindowService";

    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 Context context;

    private View root;



    private boolean isShowing = false;

    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);
        }
    };


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new LockScreenBinder(getApplicationContext());
    }


    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }


    private void initView() {


//        layoutParams.flags = WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;

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


//        hideStatusNavigationBar();

        findView(root);


        switch (LauncherManager.getInstance().getLockScreenMode()) {
            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);
    }


    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(context).getTimeConfig(TimeModeManager.getInstance(context).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(context).getTimeConfig(TimeModeManager.getInstance(context).getCurrentWorkModel());

        if (config != null) {
            Logger.e(TAG, JSON.toJSONString(config));
            tvRestModeResttime.setText(config.getGameUseTimestamp() / 60 + "分钟");
            tvRestModeUseTime.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);


    }

    public synchronized void dismiss() {
        Logger.e(TAG, "dismiss\t" + isShowing());
        if (root != null) {
            WindowManager windowManager = (WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE);
            handler.removeCallbacksAndMessages(null);
            windowManager.removeView(root);
            Logger.e(TAG, "dismiss");
            isShowing = false;
            ConfigManager.getInstance().setLockScreen(false);
        }

    }


    public synchronized void show() {
        Logger.e(TAG,"show");
        if (root != null) {

            if (root.getParent() == null) {
                addView();
            }

        } else if (root == null) {

            initView();
            addView();
        }
    }


    private void addView() {

        WindowManager windowManager = (WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE);

        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }

        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;

        layoutParams.width=WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;

        windowManager.addView(root, layoutParams);

        isShowing = true;

        Logger.e(TAG,"addView");

        ConfigManager.getInstance().setLockScreen(true);
    }


    @Override
    public void onClick(View v) {
        dismiss();
        if (v == ivCallPhone) {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getApplicationContext().startActivity(intent);
        } else if (v == ivCamera) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getApplicationContext().startActivity(intent);
        } else if (v == ivMessage) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setType("vnd.android-dir/mms-sms");
            getApplicationContext().startActivity(intent);
        }


    }


    public boolean isShowing() {
        return isShowing;
    }


    public class LockScreenBinder extends LockScreenInterface.Stub {

        public Context mContext;

        public LockScreenBinder(Context mContext) {
            this.mContext = mContext;
        }

        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

        }

        @Override
        public void lockScreen() throws RemoteException {
            show();
        }

        @Override
        public void unlockScreen() throws RemoteException {
            dismiss();
        }
    }
}
