Untitled

mail@pastecode.io avatar
unknown
plain_text
19 days ago
59 kB
1
Indexable
Never
class PrivateMessageNewDetails_Fragment : Fragment(), VolleyInterface {
    private val REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124
    var mService: WebSocketsService? = null
    var groupImage = ""
    var chatSectionHeaderArrayList: ArrayList<ChatSectionHeaderClass>? = null
    var handler: Handler? = null
    var logo = ""
    var gallaryAdepter: GallaryAdepter? = null
    var user_id = ""
    var sessionManager: SessionManager? = null
    var str_message: String? = null
    var encode_msg: String? = null
    var str_senderID = ""
    var moduleType = ""
    var senderPageId = ""
    var values: ContentValues? = null
    var imageUri: Uri? = null
    var thumbnail: Bitmap? = null
    var timer: CountDownTimer? = null
    var picturePath = " "
    var messageRecord: MessageRecord? = null
    var messageRecordOnly: MessageRecord? = null
    var messagesocket: MessageRecord.MessageChat? = null
    var privatemessageRecordOnly: MessageRecord.MessageChat? = null
    var isLast = 0
    var is_typing_status = true
    var defaultLang: DefaultLang? = null
    var permissionsNeeded: MutableList<String>? = null
    var permissionsList: MutableList<String?>? = null
    var dateHeaderString = ArrayList<String>()
    var chatSectionAdapter: ChatSectionAdapter? = null
    var onScrollListener: RecyclerView.OnScrollListener? = null
    var totalItemCount = 0
    var lastVisibleItempagecount = 0
    var current_page = 1
    var linearLayoutManager: LinearLayoutManager? = null
    var loading = false
    var isLoadMore = true
    var bundle: Bundle? = null
    var totalpages = 0
    var isGroup = false
    var groupId: String? = ""
    var groupImg: String? = null
    var endlessScrollListener: EndlessScrollListener? = null
    private val RESULT_OK = -1
    private var messageArrayList = ArrayList<MessageRecord.MessageChat?>()
    lateinit var binding: FragmentPrivateMessageDetailBinding


    companion object {
        lateinit var instance: PrivateMessageNewDetails_Fragment
        lateinit var selectImages: ArrayList<String>
        lateinit var gallaryBeansarraylist: ArrayList<GallaryBean>
        var counter = 0
    }

    private val mConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            Log.i("yash", "onServiceConnected")
            val binder = service as WebSocketsBinder
            mService = binder.service
        }

        override fun onServiceDisconnected(name: ComponentName) {
            Log.i("yash", "onServiceDisconnected")
            mService = null
        }
    }
    private val broadcastForTypingPrivate: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            // TODO Auto-generated method stub
            val types = intent.getStringExtra("type")
            if (types.equals("user_typing", ignoreCase = true)) {
                binding.linearGif.visibility = View.VISIBLE
            } else if (types.equals("user_typing_stop", ignoreCase = true)) {
                binding.linearGif.visibility = View.GONE
            }
        }
    }
    private val broadcastForTypingGroup: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            // TODO Auto-generated method stub
            val group_id = intent.getStringExtra("groupid")
            val types = intent.getStringExtra("type")
            if (types.equals("group_user_typing", ignoreCase = true)) {
                if (groupId.equals(group_id, ignoreCase = true)) {
                    binding.linearGif.visibility = View.VISIBLE
                } else {
                    binding.linearGif.visibility = View.GONE
                }
            } else if (types.equals("group_user_typing_stop", ignoreCase = true)) {
                binding.linearGif.visibility = View.GONE
            }
        }
    }
    private val broadcastforPrivateRefresh: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            // TODO Auto-generated method stub
            if (isGroup) {
                val groupid = intent.getStringExtra("groupid")
                if (groupId.equals(groupid, ignoreCase = true)) {
                    isLoadMore = true
                    current_page = 1
                    messageArrayList.clear()
                    privateGroupMessageListing
                }
            } else {
                isLoadMore = true
                current_page = 1
                messageArrayList.clear()
                privateMessageListing
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val rootView = inflater.inflate(R.layout.fragment_private_message_detail, container, false)
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding = FragmentPrivateMessageDetailBinding.bind(view)
        instance = this
        activity!!.title = ""
        if (activity is MainActivity){
            (activity as MainActivity?)!!.setDrawerState(false)
        }else{
        }
        activity!!.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
        sessionManager = SessionManager(activity)
        defaultLang = sessionManager!!.multiLangString
        handler = Handler()
        messageArrayList = ArrayList()
        selectImages = ArrayList()
        gallaryBeansarraylist = ArrayList()
        user_id = sessionManager!!.userId
        Log.d("yash", "" + user_id)
        binding.message.maxLines = 5
        binding.message.isVerticalScrollBarEnabled = true
        binding.message.movementMethod = ScrollingMovementMethod()
        chatSectionHeaderArrayList = ArrayList()
        linearLayoutManager = LinearLayoutManager(activity)
        linearLayoutManager!!.stackFromEnd = true
        linearLayoutManager!!.reverseLayout = true
        binding.recyclerView.layoutManager = linearLayoutManager
        chatSectionAdapter =
            ChatSectionAdapter(activity!!, chatSectionHeaderArrayList!!, sessionManager!!)
        binding.recyclerView.adapter = chatSectionAdapter
//        binding.recyclerView.smoothScrollToPosition(0)
        bundle = arguments
        val imageViewTarget = GlideDrawableImageViewTarget(binding.typingGif)
        Glide.with(activity).load(R.raw.typing).into(imageViewTarget)
        if (bundle != null) {
            isGroup = bundle!!.getBoolean("isGroupData")
            groupId = bundle!!.getString("groupId")
            GlobalData.chat_groupId = groupId
        }
        if (isGroup) {
            val lp = LinearLayout.LayoutParams(
                0,
                LinearLayout.LayoutParams.WRAP_CONTENT, 8.5f
            )
            binding.linearUserInfo.layoutParams = lp
            binding.btnViewProfile.visibility = View.GONE
            SessionManager.strModuleId = "0"
            SessionManager.strMenuId = "2"
        } else {
            SessionManager.strModuleId = SessionManager.private_senderId
            SessionManager.strMenuId = "12"
        }
        SessionManager.strModuleId = SessionManager.private_senderId
        SessionManager.strMenuId = "12"
        binding.btnViewProfile.text = defaultLang!!.get12ViewProfile()
        binding.message.hint = defaultLang!!.get12TypeYourMessageHere()
        val gradientDrawable = GradientDrawable()
        gradientDrawable.cornerRadius = 20.0f
        gradientDrawable.setColor(Color.parseColor(sessionManager!!.topBackColor))
        binding.btnViewProfile.background = gradientDrawable
        binding.btnViewProfile.setTextColor(Color.parseColor(sessionManager!!.topTextColor))
        binding.btnAddPhoto.setColorFilter(Color.parseColor(sessionManager!!.topBackColor))
        binding.btnSend.setColorFilter(Color.parseColor(sessionManager!!.topBackColor))
        binding.btnAddPhoto.setOnClickListener(View.OnClickListener {
            fetchPhotoFromCamera()
            //                getVideos();
        })
        messageReadChat
        binding.message.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
                if (timer != null) {
                    timer!!.cancel()
                }
                if (is_typing_status) {
                    is_typing_status = false
                    sendCommentStatusToSocket(false)
                }
                timer = object : CountDownTimer(3000, 1000) {
                    override fun onTick(millisUntilFinished: Long) {}
                    override fun onFinish() {
                        is_typing_status = true
                        sendCommentStatusToSocket(true)
                    }
                }.start()
            }

            override fun afterTextChanged(editable: Editable) {}
        })
        binding.btnSend.setOnClickListener(View.OnClickListener {
            if (sessionManager!!.isLogin) {
                activity!!.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
//                binding.message.clearFocus()
                if (isGroup) {
                    encode_msg = binding.message.text.toString().trim { it <= ' ' }
                    str_message = encode_msg
                    if (str_message.equals("", ignoreCase = true)) {
                        Log.d("AITL MESSAGE", "EMPTY")
                        if (gallaryBeansarraylist.size == 0) {
                            ToastC.show(activity, "Please select Image or Enter Message")
                        } else {
                            for (j in gallaryBeansarraylist.indices) {
                                isLast = j + 1
                                sendGroupMessageApi(gallaryBeansarraylist[j].images, str_message)
                                sessionManager!!.keyboradHidden(binding.message)
                            }
                        }
                    } else if (!str_message.equals(
                            "",
                            ignoreCase = true
                        ) && gallaryBeansarraylist.size > 0
                    ) {
                        sendGroupMessageApi("", str_message)
                        for (i in gallaryBeansarraylist.indices) {
                            sendGroupMessageApi(gallaryBeansarraylist[i].images, "")
                            sessionManager!!.keyboradHidden(binding.message)
                        }
                    } else {
                        sendGroupMessageApi("", str_message)
                        sessionManager!!.keyboradHidden(binding.message)
                    }
                } else {
                    encode_msg = binding.message.text.toString().trim { it <= ' ' }
                    str_message = encode_msg
                    if (str_message.equals("", ignoreCase = true)) {
                        Log.d("AITL MESSAGE", "EMPTY")
                        if (gallaryBeansarraylist.size == 0) {
                            ToastC.show(activity, "Please select Image or Enter Message")
                        } else {
                            if (GlobalData.isNetworkAvailable(activity)) {
                                for (j in gallaryBeansarraylist.indices) {
                                    isLast = j + 1
                                    UploadePhotoAPI(gallaryBeansarraylist[j].images)
                                }
                                selectImages.clear()
                            } else {
                                ToastC.show(activity, getString(R.string.noInernet))
                            }
                        }
                    } else {
                        if (str_message!!.trim { it <= ' ' }.length == 0) {
                            ToastC.show(activity, "Please Enter Message")
                        } else {
                            if (GlobalData.isNetworkAvailable(activity)) {
                                sessionManager!!.keyboradHidden(binding.message)
                                sendMessageApi()
                                //                                    getPrivateMessageListing();
                            } else {
                                ToastC.show(activity, "No Internet Connection")
                            }
                        }
                    }
                }
            } else {
                sessionManager!!.alertDailogLogin(activity)
            }
        })
        binding.btnViewProfile.setOnClickListener(View.OnClickListener {
            Log.d("AITL BUTTON CLICK ", "CLICK$moduleType")
            if (moduleType.equals("2", ignoreCase = true)) {
                SessionManager.AttenDeeId = str_senderID
                GlobalData.Fragment_Stack.push(GlobalData.CURRENT_FRAG)
                GlobalData.CURRENT_FRAG = GlobalData.Attendance_Detail_Fragment
                if (activity is MainActivity) {
                    (activity as MainActivity?)!!.loadFragment()
                }else if (activity is PrivateMessageActivity){
                    (activity as PrivateMessageActivity?)!!.loadFragments()
                }
            } else if (moduleType.equals("3", ignoreCase = true)) {
                SessionManager.exhibitor_id = str_senderID
                SessionManager.exhi_pageId = senderPageId
                GlobalData.Fragment_Stack.push(GlobalData.CURRENT_FRAG)
                GlobalData.CURRENT_FRAG = GlobalData.Exhibitor_Detail_Fragment
                if (activity is MainActivity) {
                    (activity as MainActivity?)!!.loadFragment()
                }else if (activity is PrivateMessageActivity){
                    (activity as PrivateMessageActivity?)!!.loadFragments()
                }
            } else if (moduleType.equals("7", ignoreCase = true)) {
                SessionManager.speaker_id = str_senderID
                GlobalData.Fragment_Stack.push(GlobalData.CURRENT_FRAG)
                GlobalData.CURRENT_FRAG = GlobalData.Speaker_Detail_Fragment
                if (activity is MainActivity) {
                    (activity as MainActivity?)!!.loadFragment()
                }else if (activity is PrivateMessageActivity){
                    (activity as PrivateMessageActivity?)!!.loadFragments()
                }
            } else if (moduleType.equals("43", ignoreCase = true)) {
                SessionManager.sponsor_id = str_senderID
                GlobalData.Fragment_Stack.push(GlobalData.CURRENT_FRAG)
                GlobalData.CURRENT_FRAG = GlobalData.Sponsor_Detail_Fragment
                if (activity is MainActivity) {
                    (activity as MainActivity?)!!.loadFragment()
                }else if (activity is PrivateMessageActivity){
                    (activity as PrivateMessageActivity?)!!.loadFragments()
                }
            }
        })
        binding.lineaerPhotoLayout.setOnClickListener(View.OnClickListener {
            if (isGroup) {
                if (messageRecord!!.groupDetails != null) {
                    GlobalData.Fragment_Stack.push(GlobalData.CURRENT_FRAG)
                    val bundle = Bundle()
                    bundle.putSerializable("Group", messageRecord!!.groupDetails)
                    GlobalData.CURRENT_FRAG = GlobalData.GroupChatDetail
                    if (activity is MainActivity) {
                        (activity as MainActivity?)!!.loadFragment()
                    }else if (activity is PrivateMessageActivity){
                        (activity as PrivateMessageActivity?)!!.loadFragments()
                    }
                }
            }
        })
        if (GlobalData.isNetworkAvailable(activity)) {
            if (isGroup) {
                messageArrayList.clear()
                privateGroupMessageListing
                //                paginationMethod();
            } else {
                messageArrayList.clear()
                privateMessageListing
                //                paginationMethod();
            }
        } else {
            ToastC.show(activity, getString(R.string.noInernet))
        }
        binding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                totalItemCount = linearLayoutManager!!.itemCount
                lastVisibleItempagecount = linearLayoutManager!!.findLastVisibleItemPosition()
                if (!loading && totalItemCount <= lastVisibleItempagecount + 7 && isLoadMore) {
                    if (current_page >= totalpages) {
                        isLoadMore = false
                    } else {
                        current_page = current_page + 1
                        if (isGroup) {
                            privateGroupMessageListingPagination
                        } else {
                            privateMessageListingPagination
                        }
                    }
                    loading = true
                }
            }
        })
    }

    fun sendCommentStatusToSocket(isstop: Boolean) {
        if (isGroup) {
            val jsonObject = JSONObject()
            try {
                jsonObject.put("event", "Notification")
                if (isstop) {
                    jsonObject.put("type", "group_user_typing_stop")
                } else {
                    jsonObject.put("type", "group_user_typing")
                }
                jsonObject.put("from_id", sessionManager!!.userId)
                jsonObject.put("group_id", groupId)
                WebSocketClient.send(jsonObject.toString())
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        } else {
            val jsonObject = JSONObject()
            try {
                jsonObject.put("event", "Notification")
                if (isstop) {
                    jsonObject.put("type", "user_typing_stop")
                } else {
                    jsonObject.put("type", "user_typing")
                }
                jsonObject.put("from_id", sessionManager!!.userId)
                jsonObject.put("to_id", str_senderID)
                WebSocketClient.send(jsonObject.toString())
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }
    }

    private val messageReadChat: Unit
        get() {
            if (sessionManager!!.isLogin) {
                if (isGroup) {
                    VolleyRequest(
                        activity,
                        VolleyRequest.Method.POST,
                        MyUrls.getMessageGroupReadByChat,
                        Param.getAllGroupMessageRead(
                              sessionManager!!.eventId,sessionManager!!.userId,groupId
                        ),
                        6,
                        false,
                        this
                    )
                } else {
                    VolleyRequest(
                        activity,
                        VolleyRequest.Method.POST,
                        MyUrls.getMessageReadByChat,
                        Param.getAllMessageRead(
                            sessionManager!!.userId,
                            "",
                            sessionManager!!.eventId,
                            SessionManager.private_senderId
                        ),
                        6,
                        false,
                        this
                    )
                }
            }
        }

    private fun UploadePhotoAPI(multipleImg: String) {
        Log.d("AITL MultipleImageAPI", multipleImg)
        VolleyRequest(
            activity,
            MyUrls.privateMessageSendImage,
            Param.message_img(File(multipleImg)),
            Param.private_image_request(
                sessionManager!!.eventId,
                sessionManager!!.userId,
                sessionManager!!.token,
                SessionManager.private_senderId
            ),
            4,
            true,
            this
        )
    }

    fun encodeEmoji(message: String?): String {
        var toServerUnicodeEncoded = ""
        return try {
            toServerUnicodeEncoded = StringEscapeUtils.escapeJava(message)
            toServerUnicodeEncoded
        } catch (e: Exception) {
            toServerUnicodeEncoded
        }
    }

    private fun sendMessageApi() {
        if (GlobalData.checkForUIDVersion()) VolleyRequest(
            activity,
            VolleyRequest.Method.POST,
            MyUrls.private_messageSendtextUid,
            Param.private_messageSend(
                sessionManager!!.eventId,
                sessionManager!!.userId,
                sessionManager!!.token,
                str_message,
                SessionManager.private_senderId
            ),
            2,
            true,
            this
        ) else VolleyRequest(
            activity,
            VolleyRequest.Method.POST,
            MyUrls.private_messageSendtext,
            Param.private_messageSend(
                sessionManager!!.eventId,
                sessionManager!!.userId,
                sessionManager!!.token,
                str_message,
                SessionManager.private_senderId
            ),
            2,
            true,
            this
        )
    }

    override fun onPause() {
        super.onPause()
        sessionManager!!.keyboradHidden(binding.message)
        activity!!.unregisterReceiver(broadcastforPrivateRefresh)
        activity!!.unregisterReceiver(broadcastForTypingPrivate)
        activity!!.unregisterReceiver(broadcastForTypingGroup)
    }

    @SuppressLint("NewApi")
    override fun onResume() {
        super.onResume()
        activity!!.registerReceiver(
            broadcastforPrivateRefresh,
            IntentFilter(GlobalData.updateMessagePrivateListing),
            Context.RECEIVER_EXPORTED
        )
        activity!!.registerReceiver(
            broadcastForTypingPrivate,
            IntentFilter(GlobalData.updateTypingMessageShow),
            Context.RECEIVER_EXPORTED
        )
        activity!!.registerReceiver(
            broadcastForTypingGroup,
            IntentFilter(GlobalData.updateTypingGroupMessageShow),
            Context.RECEIVER_EXPORTED
        )
    }

    private fun fetchPhotoFromCamera() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (isCameraPermissionGranted) {
                loadCamera()
            } else {
                requestPermission()
            }
        } else {
            loadCamera()
        }
    }

    fun camerAaddPermission(permissionsList: MutableList<String?>, permission: String?): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (activity!!.checkSelfPermission(permission!!) != PackageManager.PERMISSION_GRANTED) {
                permissionsList.add(permission)
                // Check for Rationale Option
                return shouldShowRequestPermissionRationale(permission)
            }
        }
        return true
    }

    fun requestPermission() {
        permissionsNeeded = ArrayList()
        (permissionsNeeded as ArrayList<String>).clear()
        permissionsList = ArrayList()
        (permissionsList as ArrayList<String?>).clear()
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.TIRAMISU){
            if (!camerAaddPermission(permissionsList as ArrayList<String?>, Manifest.permission.READ_MEDIA_IMAGES))
                (permissionsNeeded as ArrayList<String>).add("READ_MEDIA_IMAGES")
        }else{
            if (!camerAaddPermission(permissionsList as ArrayList<String?>, Manifest.permission.WRITE_EXTERNAL_STORAGE))
                (permissionsNeeded as ArrayList<String>).add("Write External Storage")
        }
        if (!camerAaddPermission(
                permissionsList as ArrayList<String?>,
                Manifest.permission.CAMERA
            )
        ) (permissionsNeeded as ArrayList<String>).add("Camera")
        if ((permissionsList as ArrayList<String?>).size > 0) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(
                    (permissionsList as ArrayList<String?>).toTypedArray(),
                    REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS
                )
            }
            return
        }
    }

    private fun loadCamera() {
        val item = arrayOf(defaultLang!!.get12Gallery(), defaultLang!!.get12Camera())
        val dialog = MaterialDialog.Builder(activity!!)
            .title(defaultLang!!.get12ChooseFrom())
            .items(*item)
            .itemsCallback { dialog, itemView, which, text ->
                if (which == 0) {
                    PickConfig.Builder(activity)
                        .pickMode(PickConfig.MODE_MULTIP_PICK)
                        .maxPickSize(10)
                        .spanCount(3)
                        .flag(3)
                        .toolbarColor(R.color.colorPrimary)
                        .build()
                } else if (which == 1) {
                    //camera
                    //   status = "camera";
                    values = ContentValues()
                    values!!.put(MediaStore.Images.Media.TITLE, "New Picture")
                    values!!.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera")
                    imageUri = activity!!.contentResolver.insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        values
                    )
                    val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
                    startActivityForResult(intent, 1)
                }
            }
            .build()
        dialog.show()
    }

    val isCameraPermissionGranted: Boolean
        get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.TIRAMISU){
                (activity!!.checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                        && activity!!.checkSelfPermission(Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED)

            }else{
                (activity!!.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                        && activity!!.checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)
            }
        }
        else true
    private val privateMessageListingPagination: Unit
        private get() {
            if (sessionManager!!.isLogin) {
                VolleyRequest(
                    activity,
                    VolleyRequest.Method.POST,
                    MyUrls.getPrivateUnreadMessageSenderwise,
                    Param.getAllprivateMessageSenderWise(
                        sessionManager!!.eventId,
                        sessionManager!!.userId,
                        current_page,
                        sessionManager!!.token,
                        SessionManager.private_senderId
                    ),
                    5,
                    false,
                    this
                )
            } else {
                VolleyRequest(
                    activity,
                    VolleyRequest.Method.POST,
                    MyUrls.getPrivateUnreadMessageSenderwise,
                    Param.getAllprivateMessageSenderWise(
                        sessionManager!!.eventId,
                        "",
                        current_page,
                        sessionManager!!.token,
                        SessionManager.private_senderId
                    ),
                    5,
                    false,
                    this
                )
            }
        }
    private val privateGroupMessageListingPagination: Unit
        private get() {
            if (sessionManager!!.isLogin) {
                VolleyRequest(
                    activity,
                    VolleyRequest.Method.POST,
                    MyUrls.getGroupMessageDetailListing,
                    Param.getGroupMessageDetailListing(
                        sessionManager!!.eventId,
                        sessionManager!!.userId,
                        current_page,
                        sessionManager!!.token,
                        GlobalData.chat_groupId,
                        sessionManager!!.eventType
                    ),
                    5,
                    false,
                    this
                )
            } else {
                VolleyRequest(
                    activity,
                    VolleyRequest.Method.POST,
                    MyUrls.getGroupMessageDetailListing,
                    Param.getGroupMessageDetailListing(
                        sessionManager!!.eventId,
                        "",
                        current_page,
                        sessionManager!!.token,
                        SessionManager.private_senderId,
                        sessionManager!!.eventType
                    ),
                    5,
                    false,
                    this
                )
            }
        }
    private val privateMessageListing: Unit
        private get() {
            if (sessionManager!!.isLogin) {
                VolleyRequest(
                    activity,
                    VolleyRequest.Method.POST,
                    MyUrls.getPrivateUnreadMessageSenderwise,
                    Param.getAllprivateMessageSenderWise(
                        sessionManager!!.eventId,
                        sessionManager!!.userId,
                        current_page,
                        sessionManager!!.token,
                        SessionManager.private_senderId
                    ),
                    0,
                    false,
                    this
                )
            } else {
                VolleyRequest(
                    activity,
                    VolleyRequest.Method.POST,
                    MyUrls.getPrivateUnreadMessageSenderwise,
                    Param.getAllprivateMessageSenderWise(
                        sessionManager!!.eventId,
                        "",
                        current_page,
                        sessionManager!!.token,
                        SessionManager.private_senderId
                    ),
                    0,
                    false,
                    this
                )
            }
        }
    private val privateGroupMessageListing: Unit
        private get() {
            if (sessionManager!!.isLogin) {
                VolleyRequest(
                    activity,
                    VolleyRequest.Method.POST,
                    MyUrls.getGroupMessageDetailListing,
                    Param.getGroupMessageDetailListing(
                        sessionManager!!.eventId,
                        sessionManager!!.userId,
                        current_page,
                        sessionManager!!.token,
                        GlobalData.chat_groupId,
                        sessionManager!!.eventType
                    ),
                    1,
                    true,
                    this
                )
            } else {
                VolleyRequest(
                    activity,
                    VolleyRequest.Method.POST,
                    MyUrls.getGroupMessageDetailListing,
                    Param.getGroupMessageDetailListing(
                        sessionManager!!.eventId,
                        "",
                        current_page,
                        sessionManager!!.token,
                        SessionManager.private_senderId,
                        sessionManager!!.eventType
                    ),
                    1,
                    false,
                    this
                )
            }
        }

    private fun sendGroupMessageApi(multipleImg: String, message: String?) {
        if (GlobalData.checkForUIDVersion()) VolleyRequest(
            activity,
            MyUrls.AddGroupMessages,
            Param.message_img(File(multipleImg)),
            Param.groupmessageSend(
                sessionManager!!.eventId,
                sessionManager!!.eventType,
                sessionManager!!.token,
                sessionManager!!.userId,
                groupId,
                message
            ),
            3,
            true,
            this
        ) else VolleyRequest(
            activity,
            MyUrls.AddGroupMessages,
            Param.message_img(File(multipleImg)),
            Param.groupmessageSend(
                sessionManager!!.eventId,
                sessionManager!!.eventType,
                sessionManager!!.token,
                sessionManager!!.userId,
                groupId,
                message
            ),
            3,
            true,
            this
        )
    }

    fun clearDataMember() {
        binding.message.setText("")
        gallaryBeansarraylist.clear()
        messageArrayList.clear()
        binding.linearimage.visibility =
            View.GONE
        selectImages.clear()
    }

    override fun getVolleyRequestResponse(volleyResponse: VolleyRequestResponse) {
        when (volleyResponse.type) {
            0 -> try {
                val jsonObject = JSONObject(volleyResponse.output)
                if (jsonObject.getString("success").equals("true", ignoreCase = true)) {
                    val json_data = jsonObject.getJSONObject("data")
                    setData(json_data, true)
                    loading = false
                }
            } catch (e: JSONException) {
                e.printStackTrace()
            }
            1 -> try {
                val jsonObject = JSONObject(volleyResponse.output)
                if (jsonObject.getString("success").equals("true", ignoreCase = true)) {
                    val json_data = jsonObject.getJSONObject("data")
                    setData(json_data, true)
                    messageReadChat
                    loading = false
                }
            } catch (e: JSONException) {
                e.printStackTrace()
            }
            2 -> try {
                val jsonmessage = JSONObject(volleyResponse.output)
                if (jsonmessage.getString("success").equals("true", ignoreCase = true)) {
                    if (gallaryBeansarraylist.size == 0) {
                        clearDataMember()
                        binding.message.setText("")
                        if (isGroup) {
                            val json_data = jsonmessage.getJSONObject("data")
                            setMessageData(json_data)
                        } else {
                            val json_data = jsonmessage.getJSONObject("data")
                            val jsonArray = json_data.getJSONArray("messages")
                            if (jsonArray.length() > 0) {
                                setprivateMessageData(jsonArray)
                                socketSendMessage()
                                socketSendForNotification()
                            }
                        }
                    } else {
                        var j = 0
                        while (j < gallaryBeansarraylist.size) {
                            isLast = j + 1
                            UploadePhotoAPI(gallaryBeansarraylist[j].images)
                            j++
                        }
                    }
                } else {
                    ToastC.show(activity, jsonmessage.getString("message"))
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            3 -> try {
                val jsonmessage = JSONObject(volleyResponse.output)
                if (jsonmessage.getString("success").equals("true", ignoreCase = true)) {
                    val json_data = jsonmessage.getJSONObject("data")
                    clearDataMember()
                    val jsonArray = json_data.getJSONArray("messages")
                    setMessageData(json_data)
                    if (jsonArray.length() > 0) {
                        socketSendMessage()
                        socketSendForNotification()
                    }
                    if (messageArrayList!!.size == 0) {
                        binding.txtNoDataFoud.visibility = View.VISIBLE
                    } else {
                        binding.txtNoDataFoud.visibility = View.GONE
                    }
                    loading = false
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            4 -> try {
                val imgupload = JSONObject(volleyResponse.output)
                Log.d("AITL UploadImg", imgupload.toString())
                //                    if (isLast == gallaryBeansarraylist.size()) {
                Log.d("AITL IMAGE", "ARRAYLIST GET CLEARED")
                clearDataMember()
                val json_data = imgupload.getJSONObject("data")
                val jsonArray = json_data.getJSONArray("messages")
                if (jsonArray.length() > 0) {
                    setprivateMessageData(jsonArray)
                    socketSendMessage()
                    socketSendForNotification()
                }
                loading = false
                //                    setData(json_data, false);
//                    }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            5 -> try {
                val jsonObject = JSONObject(volleyResponse.output)
                if (jsonObject.getString("success").equals("true", ignoreCase = true)) {
                    val json_data = jsonObject.getJSONObject("data")
                    setData(json_data, false)
                    loading = false
                }
            } catch (e: JSONException) {
                e.printStackTrace()
            }
            6 -> try {
                val jsonObject = JSONObject(volleyResponse.output)
                if (jsonObject.getString("success").equals("true", ignoreCase = true)) {
                }
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }
    }

    private fun socketSendForNotification() {
        val jsonObject = JSONObject()
        try {
            if (isGroup) {
                jsonObject.put("event", "Notification")
                jsonObject.put("type", "group_message")
                jsonObject.put("id", groupId)
            } else {
                jsonObject.put("event", "Notification")
                jsonObject.put("type", "private_message")
                jsonObject.put("id", str_senderID)
            }
            WebSocketClient.send(jsonObject.toString())
        } catch (e: JSONException) {
            e.printStackTrace()
        }
    }

    fun checkChannelId(): String {
        val login_user_id = sessionManager!!.userId.toInt()
        val receiver_id = SessionManager.private_senderId.toInt()
        return if (login_user_id < receiver_id) {
            login_user_id.toString() + "" + receiver_id
        } else {
            receiver_id.toString() + "" + login_user_id
        }
    }

    fun socketSendMessage() {
        val jsonObject = JSONObject()
        try {
            if (isGroup) {
                jsonObject.put("event", "Notification")
                jsonObject.put("type", "group")
                jsonObject.put("from_id", sessionManager!!.userId)
                jsonObject.put("group_id", groupId)
            } else {
                jsonObject.put("event", "Notification")
                jsonObject.put("type", "private")
                jsonObject.put("from_id", sessionManager!!.userId)
                jsonObject.put("to_id", str_senderID)
            }
            WebSocketClient.send(jsonObject.toString())
        } catch (e: JSONException) {
            e.printStackTrace()
        }
    }

    fun setData(jsonData: JSONObject, isFromFirst: Boolean) {
        if (isGroup) {
            val gson = Gson()
            messageRecord = gson.fromJson(jsonData.toString(), MessageRecord::class.java)
            messageArrayList.addAll(messageRecord!!.messages!!)
            totalpages = messageRecord!!.totalPages!!
            if (messageArrayList.size > 0) {
                binding.recyclerView.visibility = View.VISIBLE
                for (messageChat in messageArrayList) {
                    dateHeaderString.add(messageChat!!.date.toString())
                }
                chatSectionHeaderArrayList = ArrayList()
                val newList: List<String> = ArrayList(HashSet(dateHeaderString))
//                Collections.sort(newList)
//                Collections.reverse(newList)
                for (i in newList.indices) {
                    val tempmessageChatArrayList = ArrayList<MessageRecord.MessageChat?>()
                    for (j in messageArrayList.indices) {
                        if (messageArrayList[j]!!
                                .date!!.toLowerCase().contains(newList[i].toLowerCase())
                        ) {
                            messageArrayList[j]!!.isHeader = false
                            tempmessageChatArrayList.add(messageArrayList[j])
                        }
                    }
                    if (tempmessageChatArrayList.size > 0) {
                        tempmessageChatArrayList[tempmessageChatArrayList.size - 1]!!.isHeader =
                            true
                    }
//                    Collections.sort(tempmessageChatArrayList, SortComparator())
//                    Collections.reverse(tempmessageChatArrayList)
                    chatSectionHeaderArrayList!!.add(
                        ChatSectionHeaderClass(
                            tempmessageChatArrayList,
                            newList[i].toString()
                        )
                    )
                }
                setRecyclerview().execute()
            } else {
                binding.txtNoDataFoud.visibility = View.VISIBLE

            }

//            sessionManager.groupMessageData(messageRecord.getGroupDetails());
            setUpGroupDetails(messageRecord!!.groupDetails!!)
        } else {
            val gson = Gson()
            messageRecord = gson.fromJson(jsonData.toString(), MessageRecord::class.java)
            messageArrayList.addAll(messageRecord!!.messages!!)
            totalpages = messageRecord!!.totalPages!!
            if (messageArrayList.size > 0) {
                binding.recyclerView.visibility = View.VISIBLE
                for (messageChat in messageArrayList) {
                    dateHeaderString.add(messageChat!!.date.toString())
                }
                chatSectionHeaderArrayList = ArrayList()
                val newList: List<String> = ArrayList(HashSet(dateHeaderString))
                Collections.sort(newList)
                Collections.reverse(newList)
                for (i in newList.indices) {
                    val tempmessageChatArrayList = ArrayList<MessageRecord.MessageChat?>()
                    for (j in messageArrayList.indices) {
                        if (messageArrayList[j]!!
                                .date!!.toLowerCase().contains(newList[i].toLowerCase())
                        ) {
                            messageArrayList[j]!!.isHeader = false
                            tempmessageChatArrayList.add(messageArrayList[j])
                        }
                    }
                    if (tempmessageChatArrayList.size > 0) {
                        tempmessageChatArrayList[tempmessageChatArrayList.size - 1]!!.isHeader =
                            true
                    }
                    Collections.sort(tempmessageChatArrayList, SortComparator())
                    Collections.reverse(tempmessageChatArrayList)
                    chatSectionHeaderArrayList!!.add(
                        ChatSectionHeaderClass(
                            tempmessageChatArrayList,
                            newList[i].toString()
                        )
                    )
                }
                setRecyclerview().execute()
                if (current_page<=1){
                binding.recyclerView.smoothScrollToPosition(0)
                    }
            } else {
                binding.recyclerView.visibility = View.VISIBLE
            }
            setUpSenderDetails(messageRecord!!.sender_detail!!)
        }
    }

    fun setMessageData(jsonData: JSONObject) {
        val gson = Gson()
        messageRecordOnly = gson.fromJson(jsonData.toString(), MessageRecord::class.java)
        messageArrayList.addAll(messageRecordOnly!!.messages!!)
        if (messageArrayList.size > 0) {
            binding.recyclerView.visibility = View.VISIBLE
            for (messageChat in messageArrayList) {
                dateHeaderString.add(messageChat!!.date.toString())
            }
            chatSectionHeaderArrayList = ArrayList()
            val newList: List<String> = ArrayList(HashSet(dateHeaderString))
//            Collections.sort(newList)
//            Collections.reverse(newList)
            for (i in newList.indices) {
                val tempmessageChatArrayList = ArrayList<MessageRecord.MessageChat?>()
                for (j in messageArrayList.indices) {
                    if (messageArrayList[j]!!.date!!.toLowerCase()
                            .contains(newList[i].toLowerCase())
                    ) {
                        tempmessageChatArrayList.add(messageArrayList[j])
                    }
                }
                if (tempmessageChatArrayList.size > 0) {
                    tempmessageChatArrayList[tempmessageChatArrayList.size - 1]!!.isHeader = true
                }
//                Collections.sort(tempmessageChatArrayList, SortComparator())
//                Collections.reverse(tempmessageChatArrayList)
                chatSectionHeaderArrayList!!.add(
                    ChatSectionHeaderClass(
                        tempmessageChatArrayList,
                        newList[i].toString()
                    )
                )
            }
            setRecyclerview().execute()
        } else {
            binding.recyclerView.visibility = View.VISIBLE
        }
    }

    fun setprivateMessageData(jsonData: JSONArray) {
        val gson = Gson()
        for (i in 0 until jsonData.length()) {
            try {
                privatemessageRecordOnly =
                    gson.fromJson(
                        jsonData.getJSONObject(i).toString(),
                        MessageRecord.MessageChat::class.java
                    )
                messageArrayList.add(privatemessageRecordOnly)
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }
        if (messageArrayList.size > 0) {
            binding.recyclerView.visibility = View.VISIBLE
            for (messageChat in messageArrayList) {
                dateHeaderString.add(messageChat!!.date.toString())
            }
            chatSectionHeaderArrayList = ArrayList()
            val newList: List<String> = ArrayList(HashSet(dateHeaderString))
            Collections.sort(newList)
            Collections.reverse(newList)
            for (i in newList.indices) {
                val tempmessageChatArrayList = ArrayList<MessageRecord.MessageChat?>()
                for (j in messageArrayList.indices) {
                    if (messageArrayList[j]!!.date!!.toLowerCase()
                            .contains(newList[i].toLowerCase())
                    ) {
                        tempmessageChatArrayList.add(messageArrayList[j])
                    }
                }
                if (tempmessageChatArrayList.size > 0) {
                    tempmessageChatArrayList[tempmessageChatArrayList.size - 1]!!.isHeader = true
                }
                Collections.sort(tempmessageChatArrayList, SortComparator())
                Collections.reverse(tempmessageChatArrayList)
                chatSectionHeaderArrayList!!.add(
                    ChatSectionHeaderClass(
                        tempmessageChatArrayList,
                        newList[i].toString()
                    )
                )

            }

            setRecyclerview().execute()
            binding.recyclerView.smoothScrollToPosition(0)
        } else {
            binding.recyclerView.visibility = View.VISIBLE
        }
    }

    fun getRealPathFromURI(contentUri: Uri?): String {
        val proj = arrayOf(MediaStore.Images.Media.DATA)
        val cursor = activity!!.managedQuery(contentUri, proj, null, null, null)
        val column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
        cursor.moveToFirst()
        return cursor.getString(column_index)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        try {
            if (requestCode == 1) {
                Log.d("AITL", "ResultOk")
                if (resultCode == RESULT_OK) {
                    try {
                        binding.linearimage.visibility = View.VISIBLE
                        picturePath = getRealPathFromURI(imageUri)
                        thumbnail = BitmapLoader.loadBitmap(picturePath, 100, 100)
                        Log.d("Camerapath", picturePath)
                        selectImages.add(picturePath)
                        gallaryBeansarraylist.clear()
                        for (j in selectImages.indices) {
                            selectimage(
                                selectImages[j]
                            )
                            sessionManager!!.keyboradHidden(binding.message)
                            Log.d("Camera ", selectImages[j])
                        }
                    } catch (e: Exception) {
                        // TODO Auto-generated catch block
                        e.printStackTrace()
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun setUpSenderDetails(sender_detail: MessageRecord.SenderDetails) {
        if (sender_detail.module_type != null) {
            logo = if (sender_detail.module_type.equals(
                    "2",
                    ignoreCase = true
                ) || sender_detail.module_type.equals("7", ignoreCase = true)
            ) {
                MyUrls.imge_user + sender_detail.logo
            } else {
                GlobalData.getImageUrl(sessionManager) + sender_detail.logo
            }
        }
        val drawable = GradientDrawable()
        val rnd = Random()
        binding.txtUserName.text = sender_detail.sender_name
        moduleType = sender_detail.module_type.toString()
        str_senderID = sender_detail.id.toString()
        senderPageId = sender_detail.page_id!!
        if (!sender_detail.title.equals("", ignoreCase = true) && sender_detail.company_name.equals(
                "",
                ignoreCase = true
            )
        ) {
            binding.txtCompanyName.visibility = View.VISIBLE
            binding.txtCompanyName.text = sender_detail.title + " at " + sender_detail.company_name
        } else if (!sender_detail.company_name.equals("", ignoreCase = true)) {
            binding.txtCompanyName.visibility = View.VISIBLE
            binding.txtCompanyName.text = sender_detail.company_name
        } else if (!sender_detail.title.equals("", ignoreCase = true)) {
            binding.txtCompanyName.visibility = View.VISIBLE
            binding.txtCompanyName.text = sender_detail.title
        }
        if (!sender_detail.title.equals("", ignoreCase = true)) {
            if (!sender_detail.company_name.equals("", ignoreCase = true)) {
                binding.txtCompanyName.visibility = View.VISIBLE
                binding.txtCompanyName.text =
                    sender_detail.title + " at " + sender_detail.company_name
            }
        } else {
            binding.txtCompanyName.visibility = View.VISIBLE
        }
        Log.d("AITL LOGO FRAGMENT", "LOGO " + sender_detail.logo)
        GlobalData.setCheckAvtarImage(
            activity,
            sessionManager,
            sender_detail.logo,
            SessionManager.getEnable_default_avatar_mobile(),
            SessionManager.getDefault_avatar_path(),
            SessionManager.getDefault_avatar_anonymous(),
            sender_detail.sender_name,
            "",
            binding.imgProfile,
            binding.txtProfileName,
            false,
            "attendee"
        )

    }


    private fun setUpGroupDetails(groupDetails: MessageRecord.GroupDetails) {
        if (!groupDetails.name.equals("", ignoreCase = true)) {
            binding.txtUserName.text = groupDetails.name
        }
        if (!groupDetails.description.equals("", ignoreCase = true)) {
            binding.txtCompanyName.maxLines = 1
            binding.txtCompanyName.text = groupDetails.description
        }
        val drawable = GradientDrawable()
        val rnd = Random()
        if (!groupDetails.image.equals("", ignoreCase = true)) {
            groupImg = GlobalData.getImageUrl(sessionManager) + groupDetails.image
            groupImage = groupImg!!
        }
        if (groupImage.equals("", ignoreCase = true)) {
            binding.imgProress.visibility = View.GONE
            binding.imgProfile.visibility = View.GONE
            binding.txtProfileName.visibility = View.VISIBLE
            val color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256))
            if (!groupDetails.name.equals("", ignoreCase = true)) {
                binding.txtProfileName.text =
                    "" + groupDetails.name!!.uppercase(Locale.getDefault())[0]
            } else {
                binding.txtProfileName.text = "#"
            }
            if (sessionManager!!.fundrising_status.equals("1", ignoreCase = true)) {
                drawable.shape = GradientDrawable.OVAL
                drawable.setColor(Color.parseColor(sessionManager!!.funTopBackColor))
                binding.txtProfileName.setBackgroundDrawable(drawable)
                binding.txtProfileName.setTextColor(Color.parseColor(sessionManager!!.funTopTextColor))
            } else {
                drawable.shape = GradientDrawable.OVAL
                drawable.setColor(Color.parseColor(sessionManager!!.topBackColor))
                binding.txtProfileName.setBackgroundDrawable(drawable)
                binding.txtProfileName.setTextColor(Color.parseColor(sessionManager!!.topTextColor))
            }
        } else {
            Glide.with(activity)
                .load(groupImage)
                .skipMemoryCache(false)
                .listener(object : RequestListener<String?, GlideDrawable?> {
                    override fun onException(
                        e: Exception,
                        model: String?,
                        target: Target<GlideDrawable?>,
                        isFirstResource: Boolean
                    ): Boolean {
                        binding.imgProress.visibility = View.GONE
                        binding.imgProfile.visibility = View.VISIBLE
                        binding.txtProfileName.visibility = View.GONE
                        return false
                    }

                    override fun onResourceReady(
                        resource: GlideDrawable?,
                        model: String?,
                        target: Target<GlideDrawable?>,
                        isFromMemoryCache: Boolean,
                        isFirstResource: Boolean
                    ): Boolean {
                        binding.imgProress.visibility = View.GONE
                        binding.imgProfile.visibility = View.VISIBLE
                        binding.txtProfileName.visibility = View.GONE
                        return false
                    }
                })
                .thumbnail(0.7f)
                .into(binding.imgProfile)
        }
    }

    inner class setRecyclerview : AsyncTask<Void?, Void?, Void?>() {
        override fun onPostExecute(aVoid: Void?) {
            super.onPostExecute(aVoid)
            chatSectionAdapter!!.updateList(chatSectionHeaderArrayList!!)
        }

        override fun doInBackground(vararg p0: Void?): Void? {
            return null
        }
    }

    inner class SortComparator : Comparator<Any?> {
        override fun compare(o1: Any?, o2: Any?): Int {
            var time1: String? = ""
            var time2: String? = ""
            if (o1 is MessageRecord.MessageChat) {
                time1 = o1.time
            }
            if (o2 is MessageRecord.MessageChat) {
                time2 = o2.time
            }
            try {
                return SimpleDateFormat("HH:mm:ss").parse(time1)
                    .compareTo(SimpleDateFormat("HH:mm:ss").parse(time2))
            } catch (e: ParseException) {
                e.printStackTrace()
            }
            return 0
        }
    }

    fun hideVisibleLinearLayout(ishide: Int) {
        binding.linearimage.visibility = ishide
    }

    fun addSelectImages(selectImage: ArrayList<String>) {
        selectImages.addAll(selectImage)
    }

    fun selectimage(images: String?) {
        gallaryBeansarraylist.add(GallaryBean(images, "private_message"))
        Log.d("AITL", "gallaryBeansarraylist" + gallaryBeansarraylist.toString())
        Log.d("AITL", "gallaryBeansarraylistSIZE" + gallaryBeansarraylist.size)
        gallaryAdepter = GallaryAdepter(gallaryBeansarraylist, activity!!)
        val mLayoutManager: RecyclerView.LayoutManager = LinearLayoutManager(context)
        binding.recyclerImgGallaryPicker.layoutManager = mLayoutManager
        binding.recyclerImgGallaryPicker.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        binding.recyclerImgGallaryPicker.adapter = gallaryAdepter
    }
}
Leave a Comment