package com.ttstd.dialer.fragment.dialog.call;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.hjq.toast.Toaster;
import com.ttstd.dialer.R;
import com.ttstd.dialer.base.mvvm.fragment.BaseMvvmDialogFragment;
import com.ttstd.dialer.databinding.FragmentCallBinding;
import com.ttstd.dialer.db.contact.ContactInfo;
import com.ttstd.dialer.service.DialerAccessibilityService;
import com.ttstd.dialer.utils.AccessibilityServiceHelper;
import com.ttstd.dialer.utils.ApkUtils;

public class CallFragment extends BaseMvvmDialogFragment<CallViewModel, FragmentCallBinding> {
    private static final String TAG = "CallFragment";

    private static final int REQUEST_CODE_CALL = 7897;

    private Activity mContext;
    private ContactInfo mContactInfo;

    public CallFragment(ContactInfo contactInfo) {
        mContactInfo = contactInfo;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_call;
    }

    @Override
    protected void initDataBinding() {
        mContext = getActivity();
        mViewModel.setContext(mContext);
        mViewModel.setVDBinding(mViewDataBinding);
        mViewModel.setLifecycle(getLifecycleSubject());
        mViewDataBinding.setClick(new BtnClick());
    }

    @Override
    protected void initView(Bundle bundle) {

    }

    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    @Override
    public void onStart() {
        super.onStart();
        if (getDialog() != null) {
            Window window = getDialog().getWindow();
            if (window == null) return;
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            params.gravity = Gravity.BOTTOM;
            window.setAttributes(params);
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            getDialog().setCancelable(true);
            getDialog().setCanceledOnTouchOutside(true);
        }
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        DialogFragment fragment = (DialogFragment) manager.findFragmentByTag(tag);
        if (fragment != null && fragment.isAdded()
                && fragment.getDialog() != null && fragment.getDialog().isShowing()) {
            return;
        }

        try {
            FragmentTransaction ft = manager.beginTransaction();
            ft.add(this, tag);
            ft.commitAllowingStateLoss();
        } catch (Exception e) {
            Log.e(TAG, "show: " + e.getMessage());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_CALL) {
            call();
            dismiss();
        }
    }

    @Override
    public void fetchData() {

    }

    public void call() {
        try {
            String phone = mContactInfo.getPhoneNumber();
            Intent dialIntent = new Intent(Intent.ACTION_CALL);
            Uri data = Uri.parse("tel:" + phone);
            dialIntent.setData(data);
            dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(dialIntent);
        } catch (Exception e) {
            Log.e(TAG, "callNumber: " + e.getMessage());
        }


    }

    private void callWeixin(int type) {
        if (AccessibilityServiceHelper.isAccessibilityServiceEnabled(mContext, DialerAccessibilityService.class)) {
            if (ApkUtils.isInstalled(mContext, "com.tencent.mm")) {
                Intent intent = new Intent(mContext, DialerAccessibilityService.class);
                intent.putExtra("ContactInfo", mContactInfo);
                intent.putExtra("callType", type);
                mContext.startService(intent);
            } else {
                Toaster.show("微信未安装，请安装后使用");
                ApkUtils.openAppStore(mContext, "com.tencent.mm");
            }
        } else {
            Toast.makeText(mContext, "请现在打开无障碍服务中 - 拨号助手无障碍服务", Toast.LENGTH_LONG).show();
            AccessibilityServiceHelper.jumpToAccessibilitySettings(mContext);
        }
    }

    public class BtnClick {

        public void callWechatVideo(View view) {
            callWeixin(1);
            dismiss();
        }

        public void callWechatAudio(View view) {
            callWeixin(2);
            dismiss();
        }

        public void callPhone(View view) {
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CODE_CALL);
            } else {
                call();
            }
        }

        public void cancel(View view) {
            dismiss();
        }
    }
}
