//1. Tạo navigation tạo ra 2 màn hình: Login và Home, khi vào app thì hiển thị login, đúng thông tin thì tự chuyển sang home


//======== File App.js ====================================
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import LoginComp from './comp/LoginComp';
import HomeComp from './comp/HomeComp';
const StackDemo = createNativeStackNavigator();


const App = () => {
 return (
   // Bước 3: Định nghĩa Navigation
   //Tình huống 1: App chính chỉ có Nav
   <NavigationContainer>
     <StackDemo.Navigator initialRouteName='LoginComp'>
       <StackDemo.Screen name='HomeComp' component={HomeComp} options={{ title: 'Trang chủ' }} />
       <StackDemo.Screen name='LoginComp' component={LoginComp}
                       options={{headerShown: false}} />
  
     </StackDemo.Navigator>
   </NavigationContainer>


 )
}


export default App;

//======== File LoginComp.js ====================================

import { View, Text, Button } from "react-native";
import { TextInput } from "react-native-gesture-handler";
import { useState } from "react";
import AsyncStorage from '@react-native-async-storage/async-storage';
const LoginComp =( props )=>{
   const [username, setusername] = useState("");
   const [passwd, setpasswd] = useState("");
   const doLogin = ()=>{
       // kiểm tra hợp lệ dữ liệu
       if(username.length == 0) {
           alert("Chưa nhập Username"); return;
       }
       if(passwd.length == 0) {
           alert("Chưa nhập Password"); return; // lệnh return để thoát hàm login
       }
 
       // thực hiện fetch để lấy dữ liệu về
       let url_check_login = "http://192.168.75.154:3000/tb_users?username=" + username;


       fetch (url_check_login)
       .then ( (res)=>{ return res.json (); } )
       .then (   async  (res_login) => {  
           if(res_login.length != 1)
           {
               alert("Sai username hoặc lỗi trùng lặp dữ liệu");
               return;
           }else{
               // số lượng lấy được 1 bản ghi ==> kiểm tra password
               let objU = res_login[0];
               if(objU.passwd != passwd){
                   alert("Sai password"); return;
               }else{
                   // đúng password: lưu thông tin vào storage
                   try {
                       await AsyncStorage.setItem('loginInfo',  JSON.stringify( objU )   );
                       // chuyển màn hình sang màn hình home
                       props.navigation.navigate('HomeComp');


                     } catch (e) {
                       // saving error
                       console.log(e);
                     }
               }


           }


       })
 

   }
   return (
       <View style={{ margin:30}} >
           <Text>Màn hình đăng nhập</Text>
           <TextInput placeholder="Username" onChangeText={  (txt)=>{ setusername(txt)} } />
           <TextInput placeholder="Passwd" onChangeText={  (txt)=>{ setpasswd(txt)} }
                   textContentType="password" secureTextEntry={true} />
           <Button title="Login" onPress={doLogin} />


       </View>
   )
}


export default LoginComp;

 
//======== File HomeComp.js ====================================

import { View, Text } from "react-native";
import AsyncStorage from '@react-native-async-storage/async-storage';
import React,{ useState } from "react";


const HomeComp =(props)=>{
   const [loginInfo, setloginInfo] = useState({})
   const getLoginInfo = async()=>{
       try {
           const value = await AsyncStorage.getItem('loginInfo')
           if(value !== null) {
               // lấy được dữ liệu
               setloginInfo (   JSON.parse (value)  );


           }
         } catch(e) {
           // error reading value
           console.log(e);
         }
   }


   React.useEffect(() => {
       const unsubscribe = props.navigation.addListener('focus', () => {
           // khi màn hình được active thì lệnh trong này hoạt động
          getLoginInfo();
       });
  
       return unsubscribe;
     }, [props.navigation]);

   return (
       <View>
           <Text>Màn hình Home</Text>
           <Text>Username:  {loginInfo.username} -- {loginInfo.fullname} </Text>
       </View>
   )
}
export default HomeComp;