package com.baidu.rtc.sample;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.baidu.rtc.BaiduRtcRoom;
import com.baidu.rtc.sample.data.RtcClientData;
import com.baidu.rtc.sample.util.Utils;

/**
 * login
 */
public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";

    private static final int REQUEST_CAMERA_PERMISSION_ID = 100;
    private static final int REQUEST_MIC_PERMISSION_ID = 101;
    private static final int REQUEST_STORAGE_WRITE_PERMISSION_ID = 102;

    // UI references.
    private EditText mUserIDView;
    private EditText mRoomIDView;
    private CheckBox mWatchCheckbox;

    public boolean mIsCameraPermission = false;
    public boolean mIsMicPermission = false;

    private static final String DEFAULT_ROOMNAME = "112233";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        setContentView(R.layout.activity_login);

        // Set up the login form.
        mUserIDView = findViewById(R.id.userid);
        mRoomIDView = (EditText) findViewById(R.id.roomid);

        int userId = Utils.getDeviceUid();
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

        try {
            mUserIDView.setText(prefs.getString("UserID", String.valueOf(userId)));
            mRoomIDView.setText(prefs.getString("RoomID", DEFAULT_ROOMNAME));
        } catch (Exception e) {
            e.printStackTrace();
            // update from old version, using int value
            mRoomIDView.setText(prefs.getString("RoomID", DEFAULT_ROOMNAME));
        }

        mWatchCheckbox = findViewById(R.id.checkbox_watch);
        mWatchCheckbox.setChecked(prefs.getBoolean("watch_call_checked", false));
        mWatchCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                prefs.edit().putBoolean("watch_call_checked", isChecked).commit();
            }
        });

        Button mSignInButton = (Button) findViewById(R.id.sign_in_button);
        mSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                if (mUserIDView.getText().toString().isEmpty()) {
                    return;
                }
                if (mRoomIDView.getText().toString().isEmpty()) {
                    return;
                }
                if (!mayRequestPermissions()) {
                    Log.i(TAG, "no permissions!");
                    return;
                }

                attemptLogin();
                prefs.edit().putString("UserID", mUserIDView.getText().toString()).apply();
                prefs.edit().putString("RoomID", mRoomIDView.getText().toString()).apply();
            }
        });

        TextView tv = findViewById(R.id.brtc_version);
        if (tv != null) {
            tv.setText("version:" + com.baidu.rtc.config.Constraints.sdkVersion());
        }
    }

    private boolean mayRequestPermissions() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            mIsMicPermission = true;
            mIsCameraPermission = true;
            return true;
        }

        requestCameraAndMicPermissions();
        mIsCameraPermission = checkSelfPermission(Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED;
        mIsMicPermission = checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
        if (mIsCameraPermission && mIsMicPermission
                && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        return false;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CAMERA_PERMISSION_ID
                || requestCode == REQUEST_MIC_PERMISSION_ID
                || requestCode == REQUEST_STORAGE_WRITE_PERMISSION_ID) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                mayRequestPermissions();
            }
        }
    }

    private void requestCameraAndMicPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (this.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                this.requestPermissions(new String[]{Manifest.permission.CAMERA},
                        REQUEST_CAMERA_PERMISSION_ID);
            }
            if (this.checkSelfPermission(Manifest.permission.RECORD_AUDIO)
                    != PackageManager.PERMISSION_GRANTED) {
                this.requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO},
                        REQUEST_MIC_PERMISSION_ID);
            }
            if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_STORAGE_WRITE_PERMISSION_ID);
            }
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {


        // Reset errors.
        mUserIDView.setError(null);
        mRoomIDView.setError(null);

        // Store values at the time of the login attempt.
        String userid = mUserIDView.getText().toString();
        String roomid = mRoomIDView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (TextUtils.isEmpty(roomid)) {
            mRoomIDView.setError(getString(R.string.error_invalid_roomid));
            focusView = mRoomIDView;
            cancel = true;
        }

        // Check for a valid userid address.
        if (TextUtils.isEmpty(userid)) {
            mUserIDView.setError(getString(R.string.error_field_required));
            focusView = mUserIDView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            login();
        }
    }

    private void login() {
        // mic 无权限
        if (!mIsMicPermission) {
            Toast.makeText(LoginActivity.this,
                    " 缺少音频权限，无法使用通话功能", Toast.LENGTH_SHORT).show();
            return;
        }

        //  camera 无权限
        if (!mIsCameraPermission) {
            Toast.makeText(LoginActivity.this,
                    " 缺少相机权限，无法使用视频功能", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(mUserIDView.getText().toString().trim())) {
            Toast.makeText(LoginActivity.this,
                    "userId 不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent;
        RtcClientData data = new RtcClientData();
        // 读去缓存信息
        data.readCacheData(LoginActivity.this);
        data.mRoomName = mRoomIDView.getText().toString().trim();
        data.mUserId = mUserIDView.getText().toString().trim();
        data.mIsWatch = mWatchCheckbox.isChecked();
        Class<?> clazz = RoomActivity.class;
        intent = new Intent(LoginActivity.this, clazz);
        intent.putExtra("data", data);

        startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) {
            finishAfterTransition();
        } else {
            super.onBackPressed();
        }
    }

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

}