package com.example.orangesale_02;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button registerButton, loginButton;
    private EditText usernameText, paswdEdit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_login);
        init();
        //组件初始化
    }

    //组件初始化
    private void init() {
        usernameText = findViewById(R.id.username);
        paswdEdit = findViewById(R.id.password);
        loginButton = findViewById(R.id.login);
        //添加监听事件
        loginButton.setOnClickListener(this);
        registerButton = findViewById(R.id.register);
        registerButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.register:
                Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.login:

            if(validateLogin())
            {
                Intent intent1=new Intent(MainActivity.this,IndexActivity.class);
                Bundle bundle=new Bundle();
                MyDatabaseHelper myDatabaseHelper=new MyDatabaseHelper(MainActivity.this);
                bundle.putString("username",usernameText.getText().toString());
                bundle=myDatabaseHelper.queryUserInfo(myDatabaseHelper.getReadableDatabase(),bundle);
                intent1.putExtra("bundlename",bundle);
                startActivity(intent1);

            }else{
                Toast.makeText(MainActivity.this,"账号或者密码错误",Toast.LENGTH_SHORT).show();
            }
            break;
        }
    }
    private boolean validateLogin()
    {
        String username =usernameText.getText().toString();
        String password=paswdEdit.getText().toString();
        MyDatabaseHelper myDatabaseHelper=new MyDatabaseHelper(MainActivity.this);
        SQLiteDatabase sqLiteDatabase=myDatabaseHelper.getReadableDatabase();
        Cursor cursor=sqLiteDatabase.rawQuery("select *from orange_user where username=? and password=?",new String[]{username,password});
        if (cursor.getCount()>0)
        {
            return true;
        }
        return false;
    }

}
