package cc.winboll.studio.webpagesources.common;

/**
 * @Author ZhanGSKen@QQ.COM
 * @Date 2024/08/26 20:48:46
 * @Describe 登录验证对话框
 */
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.HttpAuthHandler;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.PopupMenu;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.libappbase.dialogs.YesNoAlertDialog;
import cc.winboll.studio.webpagesources.R;
import cc.winboll.studio.webpagesources.models.AuthenticationBean;
import cc.winboll.studio.webpagesources.common.AuthenticationUtils;
import com.hjq.toast.ToastUtils;
import java.util.ArrayList;

public class AuthLoginDialog {

    public static final String TAG = "AuthLoginDialog";

    WebView mWebView;
    static AuthenticationBean _mLastAuthenticationBean;
    EditText metUserName;
    EditText metPassword;
    AlertDialog mLoginAlertDialog;
    HttpAuthHandler mHttpAuthHandler;

    public AuthLoginDialog(WebView view, HttpAuthHandler httpAuthHandler, String host, String realm) {
        mWebView = view;
        mHttpAuthHandler = httpAuthHandler;
        _mLastAuthenticationBean = new AuthenticationBean();
        _mLastAuthenticationBean.setHost(host);
        _mLastAuthenticationBean.setRealm(realm);
    }

    public void show() {
        // 获取要登录的URL和已知的身份验证信息
        String authUrl = "[ " + _mLastAuthenticationBean.getHost() + " ] " + _mLastAuthenticationBean.getRealm();
        final AuthenticationUtils authenticationUtils = AuthenticationUtils.getInstance(mWebView.getContext());
        final ArrayList<AuthenticationBean> listInfo = authenticationUtils.getHostAuthenticationList(_mLastAuthenticationBean.getHost(), _mLastAuthenticationBean.getRealm());

        final View llMain = mWebView.inflate(mWebView.getContext(), R.layout.dialog_login_auth, null);
        metUserName = llMain.findViewById(R.id.viewloginhttpEditText1);
        metPassword = llMain.findViewById(R.id.viewloginhttpEditText2);
        RecyclerView recyclerView = llMain.findViewById(R.id.dialogloginauthRecyclerView1);
        recyclerView.setLayoutManager(new LinearLayoutManager(mWebView.getContext(), LinearLayoutManager.HORIZONTAL, false));
        AuthenticationBeanListAdapter adapter = new AuthenticationBeanListAdapter(listInfo);
        // 设置 RecyclerView 的适配器
        recyclerView.setAdapter(adapter);

        if (listInfo.size() > 0) {
            metUserName.setText(listInfo.get(0).getUserName());
            metPassword.setText(listInfo.get(0).getPassword());
            LogUtils.d(TAG, "listInfo setText");
        }
        // 弹窗提示用户输入账号密码
        mLoginAlertDialog = new AlertDialog.Builder(mWebView.getContext())
            .setTitle("Login Required")
            .setMessage(authUrl + "\nPlease enter your credentials:")
            .setView(llMain)
            .setPositiveButton("OK", new DialogInterface.OnClickListener(){
                @Override
                public void onClick(DialogInterface dialogInterface, int p) {
                    _mLastAuthenticationBean.setUserName(metUserName.getText().toString());
                    _mLastAuthenticationBean.setPassword(metPassword.getText().toString());
                    //LogUtils.d(TAG, "getUserName : " + _mLastAuthenticationBean.getUserName());
                    //LogUtils.d(TAG, "getPassword : " + _mLastAuthenticationBean.getPassword());
                    //LogUtils.d(TAG, "mHttpAuthHandler : " + mHttpAuthHandler);
                    // 进入网站
                    mHttpAuthHandler.proceed(_mLastAuthenticationBean.getUserName(), _mLastAuthenticationBean.getPassword());
                }
            })
            .show();
    }

    public void checkAndSaveLastAuthenticationBean() {
        if (_mLastAuthenticationBean != null) {
            // 更新身份验证信息
            if (!_mLastAuthenticationBean.getHost().isEmpty()
                && !_mLastAuthenticationBean.getRealm().isEmpty()
                && !_mLastAuthenticationBean.getUserName().isEmpty()
                && !_mLastAuthenticationBean.getPassword().isEmpty()) {
                final AuthenticationUtils authenticationUtils = AuthenticationUtils.getInstance(mWebView.getContext());
                authenticationUtils.saveAuthenticationInfo(_mLastAuthenticationBean);
                // 清理已保存，或者不需要保存的登录信息
                _mLastAuthenticationBean = null;
            }
        }
    }

    class AuthenticationBeanListAdapter extends RecyclerView.Adapter {

        ArrayList<AuthenticationBean> mDataList;
        public AuthenticationBeanListAdapter(ArrayList<AuthenticationBean> listInfo) {
            mDataList = listInfo;
        }
        @Override
        public int getItemCount() {
            return mDataList.size();
        }
        
        void deleteSMSRecycleItem(final int position) {
            YesNoAlertDialog.show(mWebView.getContext(),
                                  "密码删除提示",
                                  "请确认删除(" + mDataList.get(position).getUserName() + ")密码！"
                                  , (new YesNoAlertDialog.OnDialogResultListener(){

                                      @Override
                                      public void onYes() {
                                          AuthenticationUtils authenticationUtils = AuthenticationUtils.getInstance(mWebView.getContext());
                                          authenticationUtils.deleteAuthenticationInfo(mDataList.get(position));
                                          mDataList.remove(position);
                                          notifyDataSetChanged();
                                          ToastUtils.show("密码已删除！");
                                      }

                                      @Override
                                      public void onNo() {

                                      }
                                  }));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final AuthenticationBean item = mDataList.get(position);
            if (holder.getItemViewType() == 0) {
                final SimpleViewHolder viewHolder = (SimpleViewHolder) holder;
                viewHolder.mtvUserName.setText(item.getUserName());
                viewHolder.mCardView.setOnClickListener(new View.OnClickListener(){
                        @Override
                        public void onClick(View v) {
                            metUserName.setText(item.getUserName());
                            metPassword.setText(item.getPassword());
                        }
                    });
                viewHolder.mCardView.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View p1) {
                            // 弹出复制菜单
                            PopupMenu menu = new PopupMenu(mWebView.getContext(), viewHolder.mCardView);
                            //加载菜单资源
                            menu.getMenuInflater().inflate(R.menu.toolbar_authinfo, menu.getMenu());
                            //设置点击事件的响应
                            menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                                    @Override
                                    public boolean onMenuItemClick(MenuItem menuItem) {
                                        int nItemId = menuItem.getItemId();
                                        if (nItemId == R.id.item_delete_authinfo) {
                                            deleteSMSRecycleItem(position);
                                        }
                                        return true;
                                    }
                                });
                            //一定要调用show()来显示弹出式菜单
                            menu.show();

                            return true;
                        }
                    });
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == 0) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_authinfo, parent, false);
                return new SimpleViewHolder(view);
            }
            return null;
        }

        class SimpleViewHolder extends RecyclerView.ViewHolder {
            TextView mtvUserName;
            CardView mCardView;
            SimpleViewHolder(View itemView) {
                super(itemView);
                mtvUserName = itemView.findViewById(R.id.viewitemauthinfoTextView1);
                mCardView = itemView.findViewById(R.id.listviewauthinfoCardView1);
            }
        }

    }
}
