asd

asd
mail@pastecode.io avatar
unknown
plain_text
2 years ago
12 kB
1
Indexable
Never
package com.hit.generic.medical.project.ui.activities

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.telephony.TelephonyManager
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.firebase.ui.auth.AuthUI
import com.firebase.ui.database.FirebaseRecyclerOptions
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
// import com.google.firebase.codelab.friendlychat.databinding.ActivityMainBinding
import com.hit.generic.medical.project.ui.chat.FriendlyMessage
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.storage.StorageReference
import com.google.firebase.storage.ktx.storage
import com.hit.generic.medical.project.R
import com.hit.generic.medical.project.databinding.ActivityChatWithSpecificDoctorBinding
import com.hit.generic.medical.project.databinding.FragmentChatDoctorsBinding
import com.hit.generic.medical.project.ui.adapters.FriendlyMessageAdapter
import com.hit.generic.medical.project.ui.chat.MyButtonObserver
import com.hit.generic.medical.project.ui.chat.MyOpenDocumentContract
import com.hit.generic.medical.project.ui.chat.MyScrollToBottomObserver


class ChatWithSpecificDoctor : AppCompatActivity() {
    private lateinit var binding: ActivityChatWithSpecificDoctorBinding
    private lateinit var manager: LinearLayoutManager

    var receiverUSer:String=""

    // Firebase instance variables
    private lateinit var auth: FirebaseAuth
    private lateinit var db: FirebaseDatabase
    private lateinit var adapter: FriendlyMessageAdapter

    private val openDocument = registerForActivityResult(MyOpenDocumentContract()) { uri ->
        onImageSelected(uri)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_chat_with_specific_doctor)


        // This codelab uses View Binding
        // See: https://developer.android.com/topic/libraries/view-binding
        binding = ActivityChatWithSpecificDoctorBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // When running in debug mode, connect to the Firebase Emulator Suite
        // "10.0.2.2" is a special value which allows the Android emulator to
        // connect to "localhost" on the host computer. The port values are
        // defined in the firebase.json file.
//        if (BuildConfig.DEBUG) {
//            Firebase.database.useEmulator("10.0.2.2", 9000)
//            Firebase.auth.useEmulator("10.0.2.2", 9099)
//            Firebase.storage.useEmulator("10.0.2.2", 9199)
//        }

//        // Initialize Firebase Auth and check if the user is signed in


        auth = Firebase.auth
        val currentUser = auth.currentUser
        val tm = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val networkOperator = tm.networkOperatorName
        if ("Android" == networkOperator) {
            auth.signInWithEmailAndPassword("patient1@gmail.com", "123456")
                .addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        Log.d("Test","haeoeaao")
                        // Sign in success, update UI with the signed-in user's information
                        val user = auth.currentUser
                        mainFunction()

                    } else {
                    }
                }

        } else {
            auth.signInWithEmailAndPassword("testing2@gmail.com", "123456")
                .addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        // Sign in success, update UI with the signed-in user's information
                        val user = auth.currentUser
                    } else {
                    }
                }
        }


//        if (auth.currentUser == null) {
//            // Not signed in, launch the Sign In activity
//            startActivity(Intent(this, SignInActivity::class.java))
//            finish()
//            return
//        }

    }

    private fun mainFunction() {

        // Initialize Realtime Database

        auth = Firebase.auth
        val currentUser = auth.currentUser
        db = Firebase.database

        receiverUSer = intent.getStringExtra("receiver_user").toString()

        if(currentUser!!.displayName==receiverUSer)
            startActivity(Intent(this, MainActivity::class.java))


        val chat = db.reference.child("conversations/"+receiverUSer+"_"+currentUser!!.displayName)
        val messagesRef = chat.child("messages")
        val userTokenRef = chat.child("userToken")

        FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
            if (!task.isSuccessful) {
                return@OnCompleteListener
            }

            // Get new FCM registration token
            userTokenRef.setValue(task.result)
        })

        // val messagesRef = db.reference.child("conversations/"+ currentUser!!.getIdToken())

        // The FirebaseRecyclerAdapter class and options come from the FirebaseUI library
        // See: https://github.com/firebase/FirebaseUI-Android
        val options = FirebaseRecyclerOptions.Builder<FriendlyMessage>()
            .setQuery(messagesRef, FriendlyMessage::class.java)
            .build()
        adapter = FriendlyMessageAdapter(options, getUserName())
        manager = LinearLayoutManager(this)
        manager.stackFromEnd = true
        binding.messageRecyclerView.layoutManager = manager
        binding.messageRecyclerView.adapter = adapter

        adapter.startListening()

        // Scroll down when a new message arrives
        // See MyScrollToBottomObserver for details
        adapter.registerAdapterDataObserver(
            MyScrollToBottomObserver(binding.messageRecyclerView, adapter, manager)
        )

        // Disable the send button when there's no text in the input field
        // See MyButtonObserver for details
        binding.messageEditText.addTextChangedListener(MyButtonObserver(binding.sendButton))

        // When the send button is clicked, send a text message
        binding.sendButton.setOnClickListener {
            val friendlyMessage = FriendlyMessage(
                binding.messageEditText.text.toString(),
                getUserName(),
                getPhotoUrl(),
                null
            )
            db.reference.child("conversations/"+receiverUSer+"_"+currentUser!!.displayName).child("messages").push().setValue(friendlyMessage)
            binding.messageEditText.setText("")
        }

        // When the image button is clicked, launch the image picker
        binding.addMessageImageView.setOnClickListener {
            openDocument.launch(arrayOf("image/*"))
        }
    }

    public override fun onStart() {
        super.onStart()
        if(intent.hasExtra("receiver_user").not()){
            startActivity(Intent(this, MainActivity::class.java))
        }

        // Check if user is signed in.
//        if (auth.currentUser == null) {
//            // Not signed in, launch the Sign In activity
//            startActivity(Intent(this, SignInActivity::class.java))
//            finish()
//            return
//        }
    }

    public override fun onPause() {
        try {
            adapter.stopListening()
        }
        catch (e:Exception)
        {

        }
        super.onPause()
    }

    public override fun onResume() {
        super.onResume()
        try {
            adapter.startListening()
        }
        catch (e:Exception)
        {

        }

    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        val inflater = menuInflater
        inflater.inflate(R.menu.main_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.goBack -> {
                true
            }
            R.id.sign_out_menu -> {
                signOut()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun onImageSelected(uri: Uri) {
        Log.d(TAG, "Uri: $uri")
        val user = auth.currentUser
        val tempMessage = FriendlyMessage(null, getUserName(), getPhotoUrl(), LOADING_IMAGE_URL)
        db.reference
            .child(MESSAGES_CHILD)
            .push()
            .setValue(
                tempMessage,
                DatabaseReference.CompletionListener { databaseError, databaseReference ->
                    if (databaseError != null) {
                        Log.w(
                            TAG, "Unable to write message to database.",
                            databaseError.toException()
                        )
                        return@CompletionListener
                    }

                    // Build a StorageReference and then upload the file
                    val key = databaseReference.key
                    val storageReference = Firebase.storage
                        .getReference(user!!.uid)
                        .child(key!!)
                        .child(uri.lastPathSegment!!)
                    putImageInStorage(storageReference, uri, key)
                })
    }

    private fun putImageInStorage(storageReference: StorageReference, uri: Uri, key: String?) {
        // First upload the image to Cloud Storage
        storageReference.putFile(uri)
            .addOnSuccessListener(
                this
            ) { taskSnapshot -> // After the image loads, get a public downloadUrl for the image
                // and add it to the message.
                taskSnapshot.metadata!!.reference!!.downloadUrl
                    .addOnSuccessListener { uri ->
                        val friendlyMessage =
                            FriendlyMessage(null, getUserName(), getPhotoUrl(), uri.toString())
                        db.reference
                            .child(MESSAGES_CHILD)
                            .child(key!!)
                            .setValue(friendlyMessage)
                    }
            }
            .addOnFailureListener(this) { e ->
                Log.w(
                    TAG,
                    "Image upload task was unsuccessful.",
                    e
                )
            }
    }

    private fun signOut() {
        AuthUI.getInstance().signOut(this)
        // startActivity(Intent(this, SignInActivity::class.java))
        finish()
    }

    private fun getPhotoUrl(): String? {
        val user = auth.currentUser
        return user?.photoUrl?.toString()
    }

    private fun getUserName(): String? {
        val user = auth.currentUser
        return if (user != null) {
            user.displayName
        } else ANONYMOUS
    }

    companion object {
        private const val TAG = "MainActivity"
        const val MESSAGES_CHILD = "conversations"
        const val ANONYMOUS = "anonymous"
        private const val LOADING_IMAGE_URL = "https://www.google.com/images/spin-32.gif"
    }
}