package com.ez.ertc.meeting.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.ez.baselib.utils.NetLineConfigUtils;
import com.ez.basertc.RTCConstant;
import com.ez.baselib.utils.LogUtil;
import com.ez.ertc.meeting.ErtcEzmHelper;
import com.ez.ertc.meeting.R;
import com.ez.ertc.meeting.R2;
import com.ez.ertc.meeting.base.YsBaseActivity;
import com.ez.ertc.meeting.constant.ExtraKeys;
import com.ez.ertc.meeting.constant.MtNavigator;
import com.ez.ertc.meeting.constant.MtSets;
import com.ez.ertc.meeting.contract.JoinMeetingContract;
import com.ez.ertc.meeting.presenter.JoinMeetingPresenter;
import com.ez.ertc.meeting.utils.ViewUtil;
import com.ez.ertc.meeting.utils.permission.PermissionHelper;
import com.ez.ertc.meeting.widget.EZDialog;
import com.ez.ertc.meeting.widget.MeetingEndDialog;
import com.ez.ertc.meeting.widget.MtTextView;
import com.ez.ertc.meeting.widget.NetLineSelectDialog;
import com.ez.ertcmeeting.utils.permission.PermissionDialog;

import java.lang.reflect.Field;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author xiezuoyuan
 * @time 2020/5/8 10:57
 */
public class JoinMeetingActivity extends YsBaseActivity implements JoinMeetingContract.View{

    @BindView(R2.id.etRoomId)
    EditText etRoomId;
    @BindView(R2.id.etName)
    EditText etName;
    @BindView(R2.id.btnJoin)
    Button btnJoin;
    @BindView(R2.id.switchAudio)
    Switch switchAudio;
    @BindView(R2.id.switchVideo)
    Switch switchVideo;
    @BindView(R2.id.iconClearId)
    MtTextView iconClearId;
    @BindView(R2.id.iconClearName)
    MtTextView iconClearName;
    @BindView(R2.id.llBeauty)
    View llBeauty;
    @BindView(R2.id.tvLineId)
    TextView tvLineId;
    private boolean mEditable = true;
    private JoinMeetingContract.Presenter mPresenter;
    private MeetingEndDialog meetingEndDialog;
    private EZDialog mKickOutDialog;
    private int REQUEST_CODE_CAMERA = 500;
    private int REQUEST_CODE_MICRO = 302;
    private PermissionHelper permissionHelperCamera,permissionHelperMicrophone;

    public static void start(Activity activity) {
        if (ErtcEzmHelper.getContext() == null && activity != null){
            //规避可能出现的getContext为null的情况
            Field field = null;
            try {
                field = ErtcEzmHelper.class.getField("mContext");
                field.setAccessible(true);
                field.set(null,activity.getApplicationContext());
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        Intent starter = new Intent(activity, JoinMeetingActivity.class);
        activity.startActivity(starter);
    }

    public static void start(Context context, String action) {
        Intent starter = new Intent(context, JoinMeetingActivity.class);
        starter.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        starter.putExtra(ExtraKeys.KET_RESTART_ACTION,action);
        context.startActivity(starter);
    }

    @Override
    protected int provideLayoutId() {
        return R.layout.ys_mt_activity_join_meeting;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        etRoomId.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0){
                    btnJoin.setEnabled(etName.getText().length() > 0);
                    iconClearId.setVisibility(View.VISIBLE);
                } else {
                    btnJoin.setEnabled(false);
                    iconClearId.setVisibility(View.INVISIBLE);
                }
            }
        });
        etName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0){
                    btnJoin.setEnabled(etRoomId.getText().length() > 0);
                    iconClearName.setVisibility(mEditable ? View.VISIBLE : View.INVISIBLE);
                } else {
                    btnJoin.setEnabled(false);
                    iconClearName.setVisibility(View.INVISIBLE);
                }
            }
        });
        etRoomId.requestFocus();
        switchAudio.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if(isChecked) {
                boolean hasAudioPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
                if (!hasAudioPermission) {
                    requestToggleMicrophonePermission();
                }
            }
        });

        switchVideo.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if(isChecked) {
                boolean hasVideoPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
                if (!hasVideoPermission) {
                    requestCameraPermission(false);
                }
            }
        });
    }


    @Override
    protected void initData() {
        String name = getIntent().getStringExtra(MtNavigator.Extras.EXTRA_JOIN_NAME);
        if (!TextUtils.isEmpty(name)){
            etName.setText(name);
            etName.setEnabled(mEditable = getIntent().getBooleanExtra(MtNavigator.Extras.EXTRA_JOIN_NAME_EDITABLE,true));
        } else {
            etName.setEnabled(true);
        }
        setNetLine(NetLineConfigUtils.getNetLineId(this));
        new JoinMeetingPresenter(this);
        if (MtSets.isBeautyEnable()){
            llBeauty.setVisibility(View.VISIBLE);
        } else {
            llBeauty.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String action = intent.getStringExtra(ExtraKeys.KET_RESTART_ACTION);
        LogUtil.d("EZRTCImpl", "JoinMeetingActivity onNewIntent action:" + action);
        if (action != null){
            switch (action){
                case ExtraKeys.ACTION_KICK_OUT:
                    showKickOutDialog();
                    break;
                case ExtraKeys.ACTION_MEETING_END:
                    if (meetingEndDialog == null){
                        meetingEndDialog = new MeetingEndDialog(this, new MeetingEndDialog.OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                meetingEndDialog = null;
                            }
                        });
                    }
                    if (meetingEndDialog != null && !meetingEndDialog.isShowing()){
                        meetingEndDialog.show();
                    }
                    break;
            }
        }
    }

    private void showKickOutDialog() {
        if (mKickOutDialog == null) {
            mKickOutDialog = new EZDialog.Builder(this)
                    .setMessage(R.string.ys_mt_room_kick_out_msg)
                    .setPositiveButton(R.string.ezm_known, null)
                    .setCancelable(false)
                    .show();
        } else if (!mKickOutDialog.isShowing()){
            mKickOutDialog.show();
        }
    }

    @OnClick({R2.id.btnJoin,R2.id.iconClearId,R2.id.iconClearName,R2.id.llBeauty,R2.id.llNetwork,R2.id.llSetting, R2.id.llLineSelect})
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btnJoin) {
            if (TextUtils.isEmpty(etName.getText().toString().trim())){
                showToast(R.string.ys_mt_join_name_alert);
                return;
            }
            ViewUtil.hideKeyboard(etRoomId);
            mPresenter.onEnter();
        }else if (id == R.id.iconClearId){
            etRoomId.setText("");
            etRoomId.requestFocus();
            ViewUtil.showKeyboard(etRoomId);
        } else if (id == R.id.iconClearName){
            etName.setText("");
            etName.requestFocus();
            ViewUtil.showKeyboard(etName);
        } else if (id == R.id.llBeauty){
            requestCameraPermission(true);
        } else if (id == R.id.llNetwork){
            TestConfigActivity.start(this);
        } else if (id == R.id.llSetting) {
            DebugParamTestActivity.Companion.start(this);
        } else if(id == R.id.llLineSelect) {
            NetLineSelectDialog netLineSelectDialog = new NetLineSelectDialog(this);
            netLineSelectDialog.setSaveNetLineListener(lineId -> {
                setNetLine(lineId);
            });
            netLineSelectDialog.show();
        }
    }

    private void setNetLine(int lineId){
        tvLineId.setText(lineId == NetLineConfigUtils.LINE_GROUP_ID_OUTSIDE ?
                getResources().getString(R.string.ys_mt_line_outside) :
                getResources().getString(R.string.ys_mt_line_inside));
    }

    private void requestCameraPermission(boolean isBeauty){
        if(permissionHelperCamera == null) {
            permissionHelperCamera = new PermissionHelper(this,
                    new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_CAMERA);
        }
        permissionHelperCamera.requestCamera(new PermissionHelper.PermissionCallback() {
            @Override
            public void onPermissionGranted() {
                if(isBeauty) {
                    BeautyConfigActivity.start(JoinMeetingActivity.this);
                }
            }

            @Override
            public void onPermissionDenied() {
                PermissionDialog.Companion.requestCameraSets(JoinMeetingActivity.this);
            }
        });
    }

    private void requestToggleMicrophonePermission() {
        if (permissionHelperMicrophone == null){
            permissionHelperMicrophone = new PermissionHelper(this,
                    new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_CODE_MICRO);
        }
        permissionHelperMicrophone.requestMicrophone(new PermissionHelper.PermissionCallback() {
            @Override
            public void onPermissionGranted() {
            }

            @Override
            public void onPermissionDenied() {
                PermissionDialog.Companion.requestMicrophoneSets(JoinMeetingActivity.this);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissionHelperCamera != null && requestCode == REQUEST_CODE_CAMERA) {
            permissionHelperCamera.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
        if (permissionHelperMicrophone != null && requestCode == REQUEST_CODE_MICRO) {
            permissionHelperMicrophone.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    public void setPresenter(JoinMeetingContract.Presenter presenter) {
        mPresenter = presenter;
        mPresenter.start();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public boolean isAudioOn() {
        return switchAudio.isChecked();
    }

    @Override
    public boolean isVideoOn() {
        return switchVideo.isChecked();
    }

    @Override
    public void switchAudio(boolean checked) {
        switchAudio.setChecked(checked);
    }

    @Override
    public void switchVideo(boolean checked) {
        switchVideo.setChecked(checked);
    }

    @Override
    public String getUserId() {
        return etName.getText().toString();
    }

    @Override
    public String getRoomNo() {
        return etRoomId.getText().toString();
    }

    @Override
    public void setUserId(String userId) {
        etName.setText(userId);
    }

    @Override
    public void setRoomNo(String roomNo) {
        etRoomId.setText(roomNo);
    }

    @Override
    public void enter(String ertcToken) {
        RTCConstant.EnterParam localUserInfo = new RTCConstant.EnterParam();
        localUserInfo.roomId = getRoomNo();
        localUserInfo.userId = getUserId();
        localUserInfo.token = ertcToken;
        ErtcRoomActivity.start(this, localUserInfo,isAudioOn(),isVideoOn());
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

    }
}
