package com.handset.serialportsensor.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handset.serialportsensor.R;
import com.handset.serialportsensor.account.AccountManager;
import com.handset.serialportsensor.utils.SPUtils;

public class PasswordResetActivity extends BaseActivity {

    private EditText etOriginal;
    private EditText etNew;
    private EditText etRepeat;
    LinearLayout ll_old_pas;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reset_password);
        initView();
    }

    boolean showAdmin;

    private void initView() {
        initTitle();
        etOriginal = findViewById(R.id.et_original_password);
        etNew = findViewById(R.id.et_new_password);
        etRepeat = findViewById(R.id.et_repeat_password);
        ll_old_pas = findViewById(R.id.ll_old_pas);
        TextView btnSave = findViewById(R.id.btn_save);
        btnSave.setOnClickListener((View view) -> save());
        showAdmin = "admin".equals(AccountManager.get().getUserId());
        ll_old_pas.setVisibility(showAdmin ? View.VISIBLE : View.GONE);
    }

    private void save() {
        String pwdOld = etOriginal.getText().toString();
        String etn = etNew.getText().toString();
        String etR = etRepeat.getText().toString();
        if (AccountManager.get().isLogin()) {
            if (showAdmin) {
                String pwdOldTrue = SPUtils.getInstance(this).get("admin");
                if (!TextUtils.isEmpty(pwdOldTrue) && !pwdOld.equals(pwdOldTrue)) {
                    Toast.makeText(this, getString(R.string.old_pwd_wrong), Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            if (TextUtils.isEmpty(etn) || TextUtils.isEmpty(etR)) {
                Toast.makeText((this), getString(R.string.new_pwd_empty), Toast.LENGTH_SHORT).show();
            } else if (!etn.equals(etR)) {
                Toast.makeText((this), getString(R.string.new_pwd_not_same), Toast.LENGTH_SHORT).show();
            } else {
                SPUtils.getInstance(this).put("admin", etR);
                Toast.makeText((this), getString(R.string.pwd_change_success), Toast.LENGTH_SHORT).show();
                finish();
            }
        } else {
            Toast.makeText((this), getString(R.string.pwd_login_first), Toast.LENGTH_SHORT).show();
        }
    }

    private void initTitle() {
        ImageView ivBack = findViewById(R.id.title_back);
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener((View view) -> finish());
        TextView tvTitle = findViewById(R.id.title_text);
        tvTitle.setText(R.string.reset_password_title);
    }
}
