<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.model

class ChatMessage(val id:String="",
                  val text:String="",
                  val fromId:String="",
                  val toId:String="",
                  val sendTime:Long=0) {
}<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.activity

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import com.mucahitsahin.kotlin_chatbox_firebase.R
import com.mucahitsahin.kotlin_chatbox_firebase.model.User
import kotlinx.android.synthetic.main.activity_register.*
import java.util.*

class RegisterActivity : AppCompatActivity() {

    private lateinit var auth : FirebaseAuth

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

        auth=FirebaseAuth.getInstance()

        registerButton.setOnClickListener {
            kayitOl()
        }

        loginTextview.setOnClickListener {
            val intent= Intent(this,LoginActivity::class.java)
            startActivity(intent)
            finish()
        }


        selectPhotoImageview.setOnClickListener {
            //resim seçme ekranı açılır
            val intent=Intent(Intent.ACTION_PICK)
            intent.type="image/*"
            startActivityForResult(intent,0)
        }
    }

    var selectedPhotoUri:Uri?=null
    //resim secildikten sonra yakalama
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

        if (requestCode==0&&resultCode== Activity.RESULT_OK&& data!=null){
            selectedPhotoUri=data.data
            val bitmap=MediaStore.Images.Media.getBitmap(contentResolver,selectedPhotoUri)

            selectPhotoImageview.setImageBitmap(bitmap)
        }

        super.onActivityResult(requestCode, resultCode, data)
    }

    private fun kayitOl(){
        val email=emailRegisterEditText.text.toString()
        val sifre=passwordRegisterEditText.text.toString()
        auth.createUserWithEmailAndPassword(email,sifre).addOnCompleteListener {
            if(it.isSuccessful){
                val guncelKullanici=auth.currentUser?.email.toString()
                Toast.makeText(this,"Guncel Kullanici ${guncelKullanici}", Toast.LENGTH_LONG).show()
                val intent=Intent(this, MainActivity::class.java)
                startActivity(intent)
                finish()

                selectedPhotoUri?.let {
                    uploadImageToFirebase(it)
                }
            }

        }.addOnFailureListener {
            Toast.makeText(this,it.localizedMessage.toString(), Toast.LENGTH_LONG).show()
        }
    }

    private fun uploadImageToFirebase(uri: Uri){
        val filename=UUID.randomUUID().toString()
        val ref=FirebaseStorage.getInstance().getReference("/images/${filename}")
        ref.putFile(uri).addOnSuccessListener {
            ref.downloadUrl.addOnSuccessListener {
                saveUserToFirebaseDataBase(it.toString())
            }
        }
    }

    private fun saveUserToFirebaseDataBase(profileImageUrl:String){
        val uid=FirebaseAuth.getInstance().uid?:""
        val ref=FirebaseDatabase.getInstance().getReference("/users/${uid}")

        val user=User(uid.toString(),kullaniciAdiEditText.text.toString(),profileImageUrl)
        ref.setValue(user).addOnSuccessListener {
            //başarılı şekilde kaydoldu
        }
    }

}<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.mucahitsahin.kotlin_chatbox_firebase.R
import com.mucahitsahin.kotlin_chatbox_firebase.model.ChatMessage
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_chat.view.*
import kotlinx.android.synthetic.main.chat_me_recycler_row.view.*
import kotlinx.android.synthetic.main.new_message_recycler_row.view.*

class ChatLogRecyclerAdapter(val mesajlar:ArrayList<ChatMessage>): RecyclerView.Adapter<ChatLogRecyclerAdapter.ChatLogHolder>() {
    class ChatLogHolder(itemView:View):RecyclerView.ViewHolder(itemView) {

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChatLogHolder {
        val inflater = LayoutInflater.from(parent.context)
        val view=inflater.inflate(R.layout.chat_me_recycler_row,parent,false)
        return ChatLogHolder(view)
    }

    override fun onBindViewHolder(holder: ChatLogHolder, position: Int) {
        holder.itemView.meChatTextView.text=mesajlar[position].text
    }

    override fun getItemCount(): Int {
        return mesajlar.size
    }
}<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.activity

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import com.mucahitsahin.kotlin_chatbox_firebase.R
import kotlinx.android.synthetic.main.activity_login.*

class LoginActivity : AppCompatActivity() {

    private lateinit var auth : FirebaseAuth

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

        auth=FirebaseAuth.getInstance()

        val guncelKullanici=auth.currentUser
        if(guncelKullanici!=null){
            val intent=Intent(this,
                MainActivity::class.java)
            startActivity(intent)
            finish()
        }

        registerTextview.setOnClickListener {
            val intent=Intent(this,RegisterActivity::class.java)
            startActivity(intent)
            finish()
        }


    }

    fun girisYap(view:View){

        val email=emailRegisterEditText.text.toString()
        val sifre=passwordRegisterEditText.text.toString()

        auth.signInWithEmailAndPassword(email,sifre).addOnCompleteListener {task->

            if(task.isSuccessful){
                val guncelKullanici=auth.currentUser?.email.toString()
                Toast.makeText(this,"Guncel Kullanici ${guncelKullanici}",Toast.LENGTH_LONG).show()
                val intent=Intent(this, MainActivity::class.java)
                startActivity(intent)
                finish()
            }
        }.addOnFailureListener{
            Toast.makeText(this,it.localizedMessage.toString(),Toast.LENGTH_LONG).show()
        }

    }


}<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.mucahitsahin.kotlin_chatbox_firebase.R
import com.mucahitsahin.kotlin_chatbox_firebase.adapter.NewMessageRecyclerAdapter
import com.mucahitsahin.kotlin_chatbox_firebase.model.User
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.ViewHolder
import kotlinx.android.synthetic.main.activity_new_message.*

class NewMessageActivity : AppCompatActivity() {

    private lateinit var auth: FirebaseAuth
    private lateinit var database:FirebaseDatabase
    private lateinit var recyclerViewAdapter: NewMessageRecyclerAdapter

    //val adapter= GroupAdapter<ViewHolder>()

    val userList=ArrayList<User>()
    lateinit var layoutManager:LinearLayoutManager

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

        auth=FirebaseAuth.getInstance()
        database= FirebaseDatabase.getInstance()

        supportActionBar?.title="Kişi Seç"

        //recyclerViewNewMessage.adapter=adapter
        verileriAl()

    }

    private fun verileriAl(){

        userList.clear()
        val ref=database.getReference("/users")
        ref.addValueEventListener(object :ValueEventListener{
            override fun onDataChange(snapshot: DataSnapshot) {

                snapshot.children.forEach {
                    val user=it.getValue(User::class.java)
                    userList.add(user!!)
                }
                for (va in userList){
                    Log.d("deneme",va.username)
                    Log.d("deneme",va.profileImage)
                }

                val adapter=NewMessageRecyclerAdapter(userList,this@NewMessageActivity)
                recyclerViewNewMessage.layoutManager = LinearLayoutManager(this@NewMessageActivity)
                recyclerViewNewMessage.adapter = adapter

                Log.d("yeniMesaj","kisiler geldi")

            }

            override fun onCancelled(error: DatabaseError) {

            }

        })
    }


}<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.adapter

import com.mucahitsahin.kotlin_chatbox_firebase.R
import com.mucahitsahin.kotlin_chatbox_firebase.model.User
import com.squareup.picasso.Picasso
import com.xwray.groupie.Item
import com.xwray.groupie.ViewHolder
import kotlinx.android.synthetic.main.chat_me_recycler_row.view.*

class ChatFromItem(val text:String,val user:User):Item<ViewHolder>() {
    override fun bind(viewHolder: ViewHolder, position: Int) {
        viewHolder.itemView.meChatTextView.text=text
        val uri=user.profileImage
        Picasso.get().load(uri).into(viewHolder.itemView.meChatImageView)
    }

    override fun getLayout(): Int {
        return R.layout.chat_me_recycler_row
    }
}<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.adapter

import com.mucahitsahin.kotlin_chatbox_firebase.R
import com.mucahitsahin.kotlin_chatbox_firebase.model.User
import com.squareup.picasso.Picasso
import com.xwray.groupie.Item
import com.xwray.groupie.ViewHolder
import kotlinx.android.synthetic.main.chat_it_recycler_row.view.*

class ChatToItem(val text:String,val user: User): Item<ViewHolder>() {
    override fun bind(viewHolder: ViewHolder, position: Int) {
        viewHolder.itemView.itChatTextView.text=text
        val uri=user.profileImage
        Picasso.get().load(uri).into(viewHolder.itemView.itChatImageView)
    }

    override fun getLayout(): Int {
        return R.layout.chat_it_recycler_row
    }
}<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.activity

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.fragment.app.FragmentTransaction
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.mucahitsahin.kotlin_chatbox_firebase.R
import com.mucahitsahin.kotlin_chatbox_firebase.fragment.HomeFragment
import com.mucahitsahin.kotlin_chatbox_firebase.fragment.ProfileFragment
import com.mucahitsahin.kotlin_chatbox_firebase.model.User

class MainActivity : AppCompatActivity() {

    lateinit var homeFragment: HomeFragment
    lateinit var profileFragment: ProfileFragment

    companion object{
        var currentUser: User?=null
    }

    private fun getCurrentUser(){
        val uid=FirebaseAuth.getInstance().uid
        val ref= FirebaseDatabase.getInstance().getReference("/users/$uid")
        ref.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                currentUser=snapshot.getValue(User::class.java)
            }

            override fun onCancelled(error: DatabaseError) {
                TODO("Not yet implemented")
            }

        })
    }

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

        getCurrentUser()

        val bottomNavigation:BottomNavigationView=findViewById(R.id.bottomNavigationView)

        homeFragment= HomeFragment()
        supportFragmentManager
            .beginTransaction()
            .replace(R.id.frameLayout,homeFragment)
            .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
            .commit()

        bottomNavigation.setOnNavigationItemSelectedListener{

            when(it.itemId){

                R.id.home_navigation ->{
                    homeFragment= HomeFragment()
                    supportFragmentManager
                        .beginTransaction()
                        .replace(R.id.frameLayout,homeFragment)
                        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                        .commit()
                }
                R.id.profile_navigation ->{
                    profileFragment= ProfileFragment()
                    supportFragmentManager
                        .beginTransaction()
                        .replace(R.id.frameLayout,profileFragment)
                        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                        .commit()
                }

            }

            true
        }

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.yeni_mesaj_menu->{
                val intent=Intent(this,NewMessageActivity::class.java)
                startActivity(intent)
            }
            R.id.cikis_yap_menu->{
                FirebaseAuth.getInstance().signOut()
                val intent=Intent(this,LoginActivity::class.java)
                startActivity(intent)
                finish()
            }
        }

        return super.onOptionsItemSelected(item)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.top_menu,menu)
        return super.onCreateOptionsMenu(menu)
    }



}<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.model

import android.os.Parcelable
import kotlinx.android.parcel.Parcelize

@Parcelize
data class User(val uid:String="",val username:String="",val profileImage:String=""):Parcelable {
}<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.activity

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.*
import com.mucahitsahin.kotlin_chatbox_firebase.adapter.ChatFromItem
import com.mucahitsahin.kotlin_chatbox_firebase.adapter.ChatToItem
import com.mucahitsahin.kotlin_chatbox_firebase.R
import com.mucahitsahin.kotlin_chatbox_firebase.model.ChatMessage
import com.mucahitsahin.kotlin_chatbox_firebase.model.User
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.ViewHolder
import kotlinx.android.synthetic.main.activity_chat.*

class ChatActivity : AppCompatActivity() {


    val adapter=GroupAdapter<ViewHolder>()
    var toUser:User?=null

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


        toUser = intent.getParcelableExtra<User>("userkey")
        supportActionBar?.title=toUser!!.username

        buttonGonder.setOnClickListener {
            //mesaj gönderme
            mesajGonder()
        }

        recyclerViewMesaj.adapter=adapter
        mesajlariListele()

    }

    private fun mesajlariListele(){
        var fromId=FirebaseAuth.getInstance().uid
        var toId=toUser!!.uid

        val reference=FirebaseDatabase.getInstance().getReference("/user-messages/$fromId/$toId")
        reference.addChildEventListener(object :ChildEventListener{
            override fun onChildAdded(snapshot: DataSnapshot, previousChildName: String?) {
                val chatMessage=snapshot.getValue(ChatMessage::class.java)

                if(chatMessage!=null){
                    if(chatMessage.fromId==FirebaseAuth.getInstance().uid){
                        val user=MainActivity.currentUser
                        adapter.add(ChatFromItem(chatMessage.text,user!!))
                    }
                    else{
                        adapter.add(ChatToItem(chatMessage.text,toUser!!))
                    }
                }
            }

            override fun onChildChanged(snapshot: DataSnapshot, previousChildName: String?) {
                TODO("Not yet implemented")
            }

            override fun onChildRemoved(snapshot: DataSnapshot) {
                TODO("Not yet implemented")
            }

            override fun onChildMoved(snapshot: DataSnapshot, previousChildName: String?) {
                TODO("Not yet implemented")
            }

            override fun onCancelled(error: DatabaseError) {
                TODO("Not yet implemented")
            }

        })
    }

    private fun mesajGonder(){


        var text=editTextTextMesaj.text.toString()
        var fromId=FirebaseAuth.getInstance().uid
        val user = intent.getParcelableExtra<User>("userkey")
        var toId=user!!.uid
        var sendTime=System.currentTimeMillis()/1000

        //var reference=FirebaseDatabase.getInstance().getReference("/messages").push()
        var reference=FirebaseDatabase.getInstance().getReference("/user-messages/$fromId/$toId").push()
        var toReference=FirebaseDatabase.getInstance().getReference("/user-messages/$toId/$fromId").push()

        if(fromId==null)return

        val chatMessage=ChatMessage(reference.key!!,text,fromId,toId,sendTime)
        reference.setValue(chatMessage)
        toReference.setValue(chatMessage)

        editTextTextMesaj.text.clear()
        recyclerViewMesaj.scrollToPosition(adapter.itemCount-1)
    }
}<file_sep>package com.mucahitsahin.kotlin_chatbox_firebase.adapter

import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.auth.FirebaseAuth
import com.mucahitsahin.kotlin_chatbox_firebase.R
import com.mucahitsahin.kotlin_chatbox_firebase.activity.ChatActivity
import com.mucahitsahin.kotlin_chatbox_firebase.model.User
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.new_message_recycler_row.view.*

class NewMessageRecyclerAdapter(val userList:ArrayList<User>,val context: Context): RecyclerView.Adapter<NewMessageRecyclerAdapter.UserHolder>() {
    class UserHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserHolder {
        val inflater = LayoutInflater.from(parent.context)
        val view=inflater.inflate(R.layout.new_message_recycler_row,parent,false)
        return UserHolder(view)
    }

    override fun onBindViewHolder(holder: UserHolder, position: Int) {

            holder.itemView.recycler_row_username.text=userList[position].username
            Picasso.get().load(userList[position].profileImage).into(holder.itemView.recycler_row_imageview)
            holder.itemView.setOnClickListener {
                val intent=Intent(context,ChatActivity::class.java)
                intent.putExtra("userkey",userList[position])
                context.startActivity(intent)
            }


    }

    override fun getItemCount(): Int {
        return userList.size
    }

}