package com.example.hnpassword;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;


public class MainActivity extends AppCompatActivity {

    Button btn_copy;
    Button btn_reset;
    EditText text_date;
    TextView text_pw;

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

    private void Action()
    {
        btn_reset= findViewById(R.id.button_reset);
        btn_copy = findViewById(R.id.button_copy);
        text_date = findViewById(R.id.editText_date);
        text_pw = findViewById(R.id.editText_pw);
        text_pw.setFocusable(false);

        text_date.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                String szDate = "AQTpDPZ2+"+text_date.getText();
                text_pw.setText(stringToMD5(szDate).substring(26,32));
            }

            @Override
            public void afterTextChanged(Editable editable) {

                String szDate = "AQTpDPZ2+"+text_date.getText();
                text_pw.setText(stringToMD5(szDate).substring(26,32));

                btn_copy.setText("复制密码");
            }

        });

        btn_reset.callOnClick();


    }

    public String stringToMD5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个md5算法！");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    public void copypw(View view)
    {
        ClipboardManager cmb = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText("simple text","临时密码："+ text_pw.getText()+"，当天有效。");
        cmb.setPrimaryClip(clipData);

        btn_copy.setText("已复制");
        // return;
    }

    public void resetdata(View view)
    {
        Date date = new Date();
        text_date.setText(String.format("%tY%tm%td", date,date,date));

    }


}