ClientAMOV

mail@pastecode.io avatar
unknown
kotlin
2 years ago
5.5 kB
2
Indexable
Never
package pt.isec.tp2223g3.g3mathgame.multiplayer

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.JsonReader
import android.util.Log
import android.widget.ListView
import android.widget.TextView
import androidx.core.view.get
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.*
import com.google.firebase.database.core.view.View
import okhttp3.Address
import org.json.JSONObject
import pt.isec.tp2223g3.g3mathgame.R
import pt.isec.tp2223g3.g3mathgame.data_class.Servers
import pt.isec.tp2223g3.g3mathgame.databinding.ActivityMultiplayerClientBinding
import pt.isec.tp2223g3.g3mathgame.shared.toast
import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.io.OutputStream
import java.io.PrintWriter
import java.net.InetSocketAddress
import java.net.ServerSocket
import java.net.Socket
import kotlin.concurrent.thread

class MultiplayerClient : AppCompatActivity() {
    lateinit var binding: ActivityMultiplayerClientBinding
    private lateinit var auth: FirebaseAuth
    private lateinit var databaseReference: DatabaseReference
    private var PREFSNAME: String? = "Username"
    private val serversList: MutableList<Servers> = mutableListOf()
    private val SERVERPORT = 9999
    private val points = 0;

    private var serverSocket: ServerSocket? = null

    companion object{
        private const val CLIENT_MODE = 1

        fun getClientModeIntent(context: Context): Intent {
            return Intent(context, MultiplayerClient::class.java).apply {
                putExtra("mode", CLIENT_MODE)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        binding = ActivityMultiplayerClientBinding.inflate(layoutInflater)
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        supportActionBar?.title = getString(R.string.clientMode) // sets the menu title

        loadClientInfo()
        getServersFromFireBase()

        binding.btnJoinServer.setOnClickListener {
            val ipAddress = binding.editIpAddress.text.toString()
            if(ipAddress.isEmpty()) {
                toast(applicationContext, getString(R.string.validIpAddress))
            }
            else{
                startAsClient(ipAddress, SERVERPORT)
            }
        }

    }
    private fun startAsClient(serverIP: String, serverPort: Int = SERVERPORT) {
        val settings = applicationContext.getSharedPreferences(PREFSNAME, 0)
        val username = settings.getString("username", " ")

        thread {
            try {
                val newSocket = Socket()
                newSocket.connect(InetSocketAddress(serverIP,serverPort),5000)
                Log.i("DEBUG", "Connected")

                val reader = BufferedReader(InputStreamReader(newSocket.getInputStream()))
                val writer = PrintWriter(newSocket.getOutputStream())
                val data = JSONObject()

                data.put("Username", username)
                data.put("Points", points)
                data.put("Photo", getPhotoUrl(username))

                writer.println(data.toString())
                writer.flush()

                Log.i("DEBUG", "Sent data")
            } catch (_: Exception) {
                return@thread
            }
        }
    }


    private fun loadClientInfo(){
        val settings = applicationContext.getSharedPreferences(PREFSNAME, 0)

        if (settings.getString("username", " ") != null) {
            binding.textViewPlayerName.text = settings.getString("username", " ")

            //if no connection to firebase image from cache
            Glide.with(this /* context */)
                .load(settings.getString("photourl", ""))
                .into(binding.picPreview)
        }
    }

    private fun getPhotoUrl(username : String?) : String? {
        for(server : Servers in serversList)
            if(server.Username.equals(username))
                return server.profileImageUrl
        return null
    }

    private fun getServersFromFireBase(){
        val recyclerView = findViewById<RecyclerView>(R.id.recyclerview)
        val adapter = ServersCustomAdapter(serversList)

        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = adapter

        auth = FirebaseAuth.getInstance()
        databaseReference = FirebaseDatabase.getInstance().getReference("Game_Username")

        databaseReference.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                serversList.clear()
                if (dataSnapshot.exists()) {
                    for ((i, child) in dataSnapshot.children.withIndex()) {
                        child.getValue(Servers::class.java)?.let { serversList.add(it) }
                        adapter.notifyItemChanged(i)
                    }

                }
            }
            override fun onCancelled(error: DatabaseError) {}
        })


    }
}