SearchActivity.kt 7.3 KB
package com.example.vip

import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
//import androidx.appcompat.widget.SearchView
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import android.view.View
import android.content.Intent
import android.content.SharedPreferences
import android.util.Log
import android.view.inputmethod.InputMethodManager
import android.widget.*
import androidx.core.content.ContextCompat
import com.google.firebase.database.*
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import kotlinx.android.synthetic.main.search.*
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.ValueEventListener
import androidx.fragment.app.FragmentActivity
import androidx.core.app.ComponentActivity.ExtraData
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T




data class MemoItem(
    val Target : String = "",
    val Policy : String = "",
    val Content : String = "",
    val Link : String = "",
    val Value : String = ""
)

var database = FirebaseDatabase.getInstance().reference

class SearchActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.search)

        val prof: SharedPreferences = getSharedPreferences("policy_key", Context.MODE_PRIVATE)
        val editor: SharedPreferences.Editor=prof.edit()

        val searchList = ArrayList<SearchItem>()
        val no_search : ImageView = findViewById(R.id.no_matching) // 노서치이미지

        val searchView: SearchView
        searchView = findViewById(R.id.searchForm)
        //searchView.onActionViewExpanded(); //new Added line
        searchView.setIconifiedByDefault(false)

        ///

        database.orderByChild("Policy").addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                val size = dataSnapshot.childrenCount
                //Toast.makeText(this@SearchActivity, size.toString(), Toast.LENGTH_SHORT).show()
                if (prof.getString("len", "-1")  != size.toString()) {
                    //Toast.makeText(this@SearchActivity, "비 효율", Toast.LENGTH_SHORT).show()
                    editor.putString("len", size.toString())
                    for (memoSnapshot in dataSnapshot.children) {
                        val memo = memoSnapshot.getValue(MemoItem::class.java)
                        editor.putString(memo!!.Value, memo!!.Policy)
                    }
                    editor.commit()
                }
            }
            override fun onCancelled(p0: DatabaseError) {
            }
        })

        fun CloseKeyboard()
        {
            var view = this.currentFocus

            if(view != null)
            {
                val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
            }
        }

        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String): Boolean {

                searchList.clear()
                // 검색 버튼이 눌러졌을 때 이벤트 처리
                val layout : LinearLayout = findViewById(R.id.hashtag_linear)
                layout.setVisibility(View.GONE)

                CloseKeyboard()

                // DB 내 목록에서 맞는거 찾는 부분
                val key = arrayListOf<String>()
                for (i in 0.. (prof.getString("len", "-1")!!.toInt() -1)) {
                    val temp = prof.getString("$i", "fail")
                    val regex = "$query".toRegex()
                    val matchResult : MatchResult? = regex.find(temp.toString())
                    if (matchResult != null) {
                        key.add(temp.toString())
                    }
                }

                no_search.setVisibility(View.GONE)
                policy_scroll_view.setVisibility(View.VISIBLE)

                for (i in key) {
                    val key_query = database.orderByChild("Policy").equalTo("$i")
                    key_query.addListenerForSingleValueEvent(object : ValueEventListener {
                        override fun onDataChange(dataSnapshot: DataSnapshot) {
                            //Toast.makeText(getBaseContext(), dataSnapshot.getValue().toString(), Toast.LENGTH_SHORT).show()

                            for (memoSnapshot in dataSnapshot.children){
                                val memo = memoSnapshot.getValue(MemoItem::class.java)

                                searchList.add(
                                    SearchItem(
                                        ContextCompat.getDrawable(this@SearchActivity, R.drawable.image01)!!, memo!!.Policy
                                    )
                                )
                            }
                            val adapter=SearchAdapter(searchList)
                            searchRecyclerView.adapter=adapter

                        }

                        override fun onCancelled(p0: DatabaseError) {
                        }
                    })
                }
                if (key.size == 0) {
                        policy_scroll_view.setVisibility(View.GONE)
                        no_search.setVisibility(View.VISIBLE)
                }
                //////////


/*
                database.orderByChild("Policy").startAt("$query").endAt("$query"+"\uf8ff").addListenerForSingleValueEvent(object : ValueEventListener {
                    override fun onCancelled(p0: DatabaseError) {
                        Toast.makeText(this@SearchActivity, "실패 : $query", Toast.LENGTH_SHORT).show()
                    }
                    override fun onDataChange(dataSnapshot: DataSnapshot) {
                        if (dataSnapshot.exists() == false){ // 값 없을 때
                            policy_scroll_view.setVisibility(View.GONE)
                            no_search.setVisibility(View.VISIBLE)
                        }
                        else {
                            no_search.setVisibility(View.GONE)
                            policy_scroll_view.setVisibility(View.VISIBLE)
                        }

                        for (memoSnapshot in dataSnapshot.children){
                            val memo = memoSnapshot.getValue(MemoItem::class.java)

                            searchList.add(
                                SearchItem(
                                    ContextCompat.getDrawable(this@SearchActivity, R.drawable.image01)!!, memo!!.Policy
                                )
                            )
                        }
                        val adapter=SearchAdapter(searchList)
                        searchRecyclerView.adapter=adapter
                    }
                })*/

                return true

            }




            override fun onQueryTextChange(newText: String): Boolean {
                // 검색어가 변경되었을 때 이벤트 처리
                return false
            }
        })
    }
}