Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ConversationInfoController.kt « controllers « talk « nextcloud « com « java « main « src « app - github.com/nextcloud/talk-android.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 3100500b226fe1cad468d2e19ecdb0c3106a5172 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
/*
 * Nextcloud Talk application
 *
 * @author Mario Danic
 * Copyright (C) 2017-2018 Mario Danic <mario@lovelyhq.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.nextcloud.talk.controllers

import android.content.Context
import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import androidx.appcompat.widget.SwitchCompat
import androidx.emoji.widget.EmojiTextView
import androidx.recyclerview.widget.RecyclerView
import androidx.work.Data
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import autodagger.AutoInjector
import butterknife.BindView
import butterknife.OnClick
import com.afollestad.materialdialogs.LayoutMode.WRAP_CONTENT
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.bottomsheets.BottomSheet
import com.afollestad.materialdialogs.datetime.dateTimePicker
import com.bluelinelabs.conductor.RouterTransaction
import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.view.SimpleDraweeView
import com.nextcloud.talk.R
import com.nextcloud.talk.adapters.items.UserItem
import com.nextcloud.talk.api.NcApi
import com.nextcloud.talk.application.NextcloudTalkApplication
import com.nextcloud.talk.controllers.base.BaseController
import com.nextcloud.talk.controllers.bottomsheet.items.BasicListItemWithImage
import com.nextcloud.talk.controllers.bottomsheet.items.listItemsWithImage
import com.nextcloud.talk.events.EventStatus
import com.nextcloud.talk.jobs.DeleteConversationWorker
import com.nextcloud.talk.jobs.LeaveConversationWorker
import com.nextcloud.talk.models.database.UserEntity
import com.nextcloud.talk.models.json.conversations.Conversation
import com.nextcloud.talk.models.json.conversations.RoomOverall
import com.nextcloud.talk.models.json.converters.EnumNotificationLevelConverter
import com.nextcloud.talk.models.json.generic.GenericOverall
import com.nextcloud.talk.models.json.participants.Participant
import com.nextcloud.talk.models.json.participants.ParticipantsOverall
import com.nextcloud.talk.utils.ApiUtils
import com.nextcloud.talk.utils.DateUtils
import com.nextcloud.talk.utils.DisplayUtils
import com.nextcloud.talk.utils.bundle.BundleKeys
import com.nextcloud.talk.utils.preferences.preferencestorage.DatabaseStorageModule
import com.yarolegovich.lovelydialog.LovelySaveStateHandler
import com.yarolegovich.lovelydialog.LovelyStandardDialog
import com.yarolegovich.mp.MaterialChoicePreference
import com.yarolegovich.mp.MaterialPreferenceCategory
import com.yarolegovich.mp.MaterialPreferenceScreen
import com.yarolegovich.mp.MaterialStandardPreference
import com.yarolegovich.mp.MaterialSwitchPreference
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.Calendar
import java.util.Collections
import java.util.Comparator
import java.util.Locale
import javax.inject.Inject

@AutoInjector(NextcloudTalkApplication::class)
class ConversationInfoController(args: Bundle) : BaseController(args), FlexibleAdapter.OnItemClickListener {

    @BindView(R.id.notification_settings)
    lateinit var notificationsPreferenceScreen: MaterialPreferenceScreen

    @BindView(R.id.progressBar)
    lateinit var progressBar: ProgressBar

    @BindView(R.id.conversation_info_message_notifications)
    lateinit var messageNotificationLevel: MaterialChoicePreference

    @BindView(R.id.webinar_settings)
    lateinit var conversationInfoWebinar: MaterialPreferenceScreen

    @BindView(R.id.conversation_info_lobby)
    lateinit var conversationInfoLobby: MaterialSwitchPreference

    @BindView(R.id.conversation_info_name)
    lateinit var nameCategoryView: MaterialPreferenceCategory

    @BindView(R.id.start_time_preferences)
    lateinit var startTimeView: MaterialStandardPreference

    @BindView(R.id.avatar_image)
    lateinit var conversationAvatarImageView: SimpleDraweeView

    @BindView(R.id.display_name_text)
    lateinit var conversationDisplayName: EmojiTextView

    @BindView(R.id.participants_list_category)
    lateinit var participantsListCategory: MaterialPreferenceCategory

    @BindView(R.id.addParticipantsAction)
    lateinit var addParticipantsAction: MaterialStandardPreference

    @BindView(R.id.recycler_view)
    lateinit var recyclerView: RecyclerView

    @BindView(R.id.deleteConversationAction)
    lateinit var deleteConversationAction: MaterialStandardPreference

    @BindView(R.id.leaveConversationAction)
    lateinit var leaveConversationAction: MaterialStandardPreference

    @BindView(R.id.ownOptions)
    lateinit var ownOptionsCategory: MaterialPreferenceCategory

    @BindView(R.id.muteCalls)
    lateinit var muteCalls: MaterialSwitchPreference

    @set:Inject
    lateinit var ncApi: NcApi

    @set:Inject
    lateinit var context: Context

    @set:Inject
    lateinit var eventBus: EventBus

    private val conversationToken: String?
    private val conversationUser: UserEntity?
    private val hasAvatarSpacing: Boolean
    private val credentials: String?
    private var roomDisposable: Disposable? = null
    private var participantsDisposable: Disposable? = null

    private var databaseStorageModule: DatabaseStorageModule? = null
    private var conversation: Conversation? = null

    private var adapter: FlexibleAdapter<UserItem>? = null
    private var recyclerViewItems: MutableList<UserItem> = ArrayList()

    private var saveStateHandler: LovelySaveStateHandler? = null

    private val workerData: Data?
        get() {
            if (!TextUtils.isEmpty(conversationToken) && conversationUser != null) {
                val data = Data.Builder()
                data.putString(BundleKeys.KEY_ROOM_TOKEN, conversationToken)
                data.putLong(BundleKeys.KEY_INTERNAL_USER_ID, conversationUser.id)
                return data.build()
            }

            return null
        }

    init {
        setHasOptionsMenu(true)
        NextcloudTalkApplication.sharedApplication?.componentApplication?.inject(this)
        conversationUser = args.getParcelable(BundleKeys.KEY_USER_ENTITY)
        conversationToken = args.getString(BundleKeys.KEY_ROOM_TOKEN)
        hasAvatarSpacing = args.getBoolean(BundleKeys.KEY_ROOM_ONE_TO_ONE, false)
        credentials = ApiUtils.getCredentials(conversationUser!!.username, conversationUser.token)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                router.popCurrentController()
                return true
            }
            else -> return super.onOptionsItemSelected(item)
        }
    }

    override fun inflateView(inflater: LayoutInflater, container: ViewGroup): View {
        return inflater.inflate(R.layout.controller_conversation_info, container, false)
    }

    override fun onAttach(view: View) {
        super.onAttach(view)
        eventBus.register(this)

        if (databaseStorageModule == null) {
            databaseStorageModule = DatabaseStorageModule(conversationUser!!, conversationToken)
        }

        notificationsPreferenceScreen.setStorageModule(databaseStorageModule)
        conversationInfoWebinar.setStorageModule(databaseStorageModule)

        fetchRoomInfo()
    }

    override fun onViewBound(view: View) {
        super.onViewBound(view)

        if (saveStateHandler == null) {
            saveStateHandler = LovelySaveStateHandler()
        }

        addParticipantsAction.visibility = View.GONE
    }

    private fun setupWebinaryView() {
        if (conversationUser!!.hasSpreedFeatureCapability("webinary-lobby") &&
            (
                conversation!!.type == Conversation.ConversationType.ROOM_GROUP_CALL ||
                    conversation!!.type == Conversation.ConversationType.ROOM_PUBLIC_CALL
                ) &&
            conversation!!.canModerate(conversationUser)
        ) {
            conversationInfoWebinar.visibility = View.VISIBLE

            val isLobbyOpenToModeratorsOnly =
                conversation!!.lobbyState == Conversation.LobbyState.LOBBY_STATE_MODERATORS_ONLY
            (conversationInfoLobby.findViewById<View>(R.id.mp_checkable) as SwitchCompat)
                .isChecked = isLobbyOpenToModeratorsOnly

            reconfigureLobbyTimerView()

            startTimeView.setOnClickListener {
                MaterialDialog(activity!!, BottomSheet(WRAP_CONTENT)).show {
                    val currentTimeCalendar = Calendar.getInstance()
                    if (conversation!!.lobbyTimer != null && conversation!!.lobbyTimer != 0L) {
                        currentTimeCalendar.timeInMillis = conversation!!.lobbyTimer * 1000
                    }

                    dateTimePicker(
                        minDateTime = Calendar.getInstance(),
                        requireFutureDateTime =
                        true,
                        currentDateTime = currentTimeCalendar,
                        show24HoursView = true,
                        dateTimeCallback = { _,
                            dateTime ->
                            reconfigureLobbyTimerView(dateTime)
                            submitLobbyChanges()
                        }
                    )
                }
            }

            (conversationInfoLobby.findViewById<View>(R.id.mp_checkable) as SwitchCompat).setOnCheckedChangeListener { _, _ ->
                reconfigureLobbyTimerView()
                submitLobbyChanges()
            }
        } else {
            conversationInfoWebinar.visibility = View.GONE
        }
    }

    fun reconfigureLobbyTimerView(dateTime: Calendar? = null) {
        val isChecked = (conversationInfoLobby.findViewById<View>(R.id.mp_checkable) as SwitchCompat).isChecked

        if (dateTime != null && isChecked) {
            conversation!!.lobbyTimer = (dateTime.timeInMillis - (dateTime.time.seconds * 1000)) / 1000
        } else if (!isChecked) {
            conversation!!.lobbyTimer = 0
        }

        conversation!!.lobbyState = if (isChecked) Conversation.LobbyState
            .LOBBY_STATE_MODERATORS_ONLY else Conversation.LobbyState.LOBBY_STATE_ALL_PARTICIPANTS

        if (conversation!!.lobbyTimer != null && conversation!!.lobbyTimer != java.lang.Long.MIN_VALUE && conversation!!.lobbyTimer != 0L) {
            startTimeView.setSummary(DateUtils.getLocalDateStringFromTimestampForLobby(conversation!!.lobbyTimer))
        } else {
            startTimeView.setSummary(R.string.nc_manual)
        }

        if (isChecked) {
            startTimeView.visibility = View.VISIBLE
        } else {
            startTimeView.visibility = View.GONE
        }
    }

    fun submitLobbyChanges() {
        val state = if (
            (
                conversationInfoLobby.findViewById<View>(
                    R.id.mp_checkable
                ) as SwitchCompat
                ).isChecked
        ) 1 else 0

        val apiVersion = ApiUtils.getConversationApiVersion(conversationUser, intArrayOf(ApiUtils.APIv4, 1))

        ncApi.setLobbyForConversation(
            ApiUtils.getCredentials(conversationUser!!.username, conversationUser.token),
            ApiUtils.getUrlForRoomWebinaryLobby(apiVersion, conversationUser.baseUrl, conversation!!.token),
            state,
            conversation!!.lobbyTimer
        )
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<GenericOverall> {
                override fun onComplete() {
                }

                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: GenericOverall) {
                }

                override fun onError(e: Throwable) {
                }
            })
    }

    private fun showLovelyDialog(dialogId: Int, savedInstanceState: Bundle) {
        when (dialogId) {
            ID_DELETE_CONVERSATION_DIALOG -> showDeleteConversationDialog(savedInstanceState)
            else -> {
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(eventStatus: EventStatus) {
        getListOfParticipants()
    }

    override fun onDetach(view: View) {
        super.onDetach(view)
        eventBus.unregister(this)
    }

    private fun showDeleteConversationDialog(savedInstanceState: Bundle?) {
        if (activity != null) {
            LovelyStandardDialog(activity, LovelyStandardDialog.ButtonLayout.HORIZONTAL)
                .setTopColorRes(R.color.nc_darkRed)
                .setIcon(
                    DisplayUtils.getTintedDrawable(
                        context!!.resources,
                        R.drawable.ic_delete_black_24dp, R.color.bg_default
                    )
                )
                .setPositiveButtonColor(context!!.resources.getColor(R.color.nc_darkRed))
                .setTitle(R.string.nc_delete_call)
                .setMessage(R.string.nc_delete_conversation_more)
                .setPositiveButton(R.string.nc_delete) { deleteConversation() }
                .setNegativeButton(R.string.nc_cancel, null)
                .setInstanceStateHandler(ID_DELETE_CONVERSATION_DIALOG, saveStateHandler!!)
                .setSavedInstanceState(savedInstanceState)
                .show()
        }
    }

    override fun onSaveViewState(view: View, outState: Bundle) {
        saveStateHandler!!.saveInstanceState(outState)
        super.onSaveViewState(view, outState)
    }

    override fun onRestoreViewState(view: View, savedViewState: Bundle) {
        super.onRestoreViewState(view, savedViewState)
        if (LovelySaveStateHandler.wasDialogOnScreen(savedViewState)) {
            // Dialog won't be restarted automatically, so we need to call this method.
            // Each dialog knows how to restore its state
            showLovelyDialog(LovelySaveStateHandler.getSavedDialogId(savedViewState), savedViewState)
        }
    }

    private fun setupAdapter() {
        if (activity != null) {
            if (adapter == null) {
                adapter = FlexibleAdapter(recyclerViewItems, activity, true)
            }

            val layoutManager = SmoothScrollLinearLayoutManager(activity)
            recyclerView.layoutManager = layoutManager
            recyclerView.setHasFixedSize(true)
            recyclerView.adapter = adapter

            adapter!!.addListener(this)
        }
    }

    private fun handleParticipants(participants: List<Participant>) {
        var userItem: UserItem
        var participant: Participant

        recyclerViewItems = ArrayList()
        var ownUserItem: UserItem? = null

        for (i in participants.indices) {
            participant = participants[i]
            userItem = UserItem(participant, conversationUser, null)
            userItem.isOnline = !participant.sessionId.equals("0")
            if (!TextUtils.isEmpty(participant.userId) && participant.userId == conversationUser!!.userId) {
                ownUserItem = userItem
                ownUserItem.model.sessionId = "-1"
                ownUserItem.isOnline = true
            } else {
                recyclerViewItems.add(userItem)
            }
        }

        Collections.sort(recyclerViewItems, UserItemComparator())

        if (ownUserItem != null) {
            recyclerViewItems.add(0, ownUserItem)
        }

        setupAdapter()

        participantsListCategory.visibility = View.VISIBLE
        adapter!!.updateDataSet(recyclerViewItems)
    }

    override fun getTitle(): String? {
        return if (hasAvatarSpacing) {
            " " + resources!!.getString(R.string.nc_conversation_menu_conversation_info)
        } else {
            resources!!.getString(R.string.nc_conversation_menu_conversation_info)
        }
    }

    private fun getListOfParticipants() {
        var apiVersion = 1
        // FIXME Fix API checking with guests?
        if (conversationUser != null) {
            apiVersion = ApiUtils.getConversationApiVersion(conversationUser, intArrayOf(1))
        }

        ncApi.getPeersForCall(
            credentials,
            ApiUtils.getUrlForParticipants(apiVersion, conversationUser!!.baseUrl, conversationToken)
        )
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<ParticipantsOverall> {
                override fun onSubscribe(d: Disposable) {
                    participantsDisposable = d
                }

                override fun onNext(participantsOverall: ParticipantsOverall) {
                    handleParticipants(participantsOverall.ocs.data)
                }

                override fun onError(e: Throwable) {
                }

                override fun onComplete() {
                    participantsDisposable!!.dispose()
                }
            })
    }

    @OnClick(R.id.addParticipantsAction)
    internal fun addParticipants() {
        val bundle = Bundle()
        val existingParticipantsId = arrayListOf<String>()

        recyclerViewItems.forEach {
            val userItem = it as UserItem
            existingParticipantsId.add(userItem.model.userId)
        }

        bundle.putBoolean(BundleKeys.KEY_ADD_PARTICIPANTS, true)
        bundle.putStringArrayList(BundleKeys.KEY_EXISTING_PARTICIPANTS, existingParticipantsId)
        bundle.putString(BundleKeys.KEY_TOKEN, conversation!!.token)

        getRouter().pushController(
            (
                RouterTransaction.with(
                    ContactsController(bundle)
                )
                    .pushChangeHandler(
                        HorizontalChangeHandler()
                    )
                    .popChangeHandler(
                        HorizontalChangeHandler()
                    )
                )
        )
    }

    @OnClick(R.id.leaveConversationAction)
    internal fun leaveConversation() {
        workerData?.let {
            WorkManager.getInstance().enqueue(
                OneTimeWorkRequest.Builder(
                    LeaveConversationWorker::class
                        .java
                ).setInputData(it).build()
            )
            popTwoLastControllers()
        }
    }

    private fun deleteConversation() {
        workerData?.let {
            WorkManager.getInstance().enqueue(
                OneTimeWorkRequest.Builder(
                    DeleteConversationWorker::class.java
                ).setInputData(it).build()
            )
            popTwoLastControllers()
        }
    }

    @OnClick(R.id.deleteConversationAction)
    internal fun deleteConversationClick() {
        showDeleteConversationDialog(null)
    }

    private fun popTwoLastControllers() {
        var backstack = router.backstack
        backstack = backstack.subList(0, backstack.size - 2)
        router.setBackstack(backstack, HorizontalChangeHandler())
    }

    private fun fetchRoomInfo() {
        var apiVersion = 1
        // FIXME Fix API checking with guests?
        if (conversationUser != null) {
            apiVersion = ApiUtils.getConversationApiVersion(conversationUser, intArrayOf(ApiUtils.APIv4, 1))
        }

        ncApi.getRoom(credentials, ApiUtils.getUrlForRoom(apiVersion, conversationUser!!.baseUrl, conversationToken))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<RoomOverall> {
                override fun onSubscribe(d: Disposable) {
                    roomDisposable = d
                }

                override fun onNext(roomOverall: RoomOverall) {
                    conversation = roomOverall.ocs.data

                    val conversationCopy = conversation

                    if (conversationCopy!!.canModerate(conversationUser)) {
                        addParticipantsAction.visibility = View.VISIBLE
                    } else {
                        addParticipantsAction.visibility = View.GONE
                    }

                    if (isAttached && (!isBeingDestroyed || !isDestroyed)) {
                        ownOptionsCategory.visibility = View.VISIBLE

                        setupWebinaryView()

                        if (!conversation!!.canLeave(conversationUser)) {
                            leaveConversationAction.visibility = View.GONE
                        } else {
                            leaveConversationAction.visibility = View.VISIBLE
                        }

                        if (!conversation!!.canModerate(conversationUser)) {
                            deleteConversationAction.visibility = View.GONE
                        } else {
                            deleteConversationAction.visibility = View.VISIBLE
                        }

                        if (Conversation.ConversationType.ROOM_SYSTEM == conversation!!.type) {
                            muteCalls.visibility = View.GONE
                        }

                        getListOfParticipants()

                        progressBar.visibility = View.GONE

                        nameCategoryView.visibility = View.VISIBLE

                        conversationDisplayName.text = conversation!!.displayName

                        loadConversationAvatar()
                        adjustNotificationLevelUI()

                        notificationsPreferenceScreen.visibility = View.VISIBLE
                    }
                }

                override fun onError(e: Throwable) {
                }

                override fun onComplete() {
                    roomDisposable!!.dispose()
                }
            })
    }

    private fun adjustNotificationLevelUI() {
        if (conversation != null) {
            if (conversationUser != null && conversationUser.hasSpreedFeatureCapability("notification-levels")) {
                messageNotificationLevel.isEnabled = true
                messageNotificationLevel.alpha = 1.0f

                if (conversation!!.notificationLevel != Conversation.NotificationLevel.DEFAULT) {
                    val stringValue: String =
                        when (EnumNotificationLevelConverter().convertToInt(conversation!!.notificationLevel)) {
                            1 -> "always"
                            2 -> "mention"
                            3 -> "never"
                            else -> "mention"
                        }

                    messageNotificationLevel.value = stringValue
                } else {
                    setProperNotificationValue(conversation)
                }
            } else {
                messageNotificationLevel.isEnabled = false
                messageNotificationLevel.alpha = 0.38f
                setProperNotificationValue(conversation)
            }
        }
    }

    private fun setProperNotificationValue(conversation: Conversation?) {
        if (conversation!!.type == Conversation.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL) {
            // hack to see if we get mentioned always or just on mention
            if (conversationUser!!.hasSpreedFeatureCapability("mention-flag")) {
                messageNotificationLevel.value = "always"
            } else {
                messageNotificationLevel.value = "mention"
            }
        } else {
            messageNotificationLevel.value = "mention"
        }
    }

    private fun loadConversationAvatar() {
        when (conversation!!.type) {
            Conversation.ConversationType.ROOM_TYPE_ONE_TO_ONE_CALL -> if (
                !TextUtils.isEmpty(conversation!!.name)
            ) {
                val draweeController = Fresco.newDraweeControllerBuilder()
                    .setOldController(conversationAvatarImageView.controller)
                    .setAutoPlayAnimations(true)
                    .setImageRequest(
                        DisplayUtils.getImageRequestForUrl(
                            ApiUtils.getUrlForAvatarWithName(
                                conversationUser!!.baseUrl,
                                conversation!!.name, R.dimen.avatar_size_big
                            ),
                            conversationUser
                        )
                    )
                    .build()
                conversationAvatarImageView.controller = draweeController
            }
            Conversation.ConversationType.ROOM_GROUP_CALL -> conversationAvatarImageView.hierarchy.setPlaceholderImage(
                R.drawable.ic_circular_group
            )
            Conversation.ConversationType.ROOM_PUBLIC_CALL -> conversationAvatarImageView.hierarchy.setPlaceholderImage(
                R.drawable.ic_circular_link
            )
            Conversation.ConversationType.ROOM_SYSTEM -> {
                val layers = arrayOfNulls<Drawable>(2)
                layers[0] = context.getDrawable(R.drawable.ic_launcher_background)
                layers[1] = context.getDrawable(R.drawable.ic_launcher_foreground)
                val layerDrawable = LayerDrawable(layers)
                conversationAvatarImageView.hierarchy.setPlaceholderImage(DisplayUtils.getRoundedDrawable(layerDrawable))
            }

            else -> {
            }
        }
    }

    override fun onItemClick(view: View?, position: Int): Boolean {
        val userItem = adapter?.getItem(position) as UserItem
        val participant = userItem.model

        if (participant.userId != conversationUser!!.userId) {
            var items = mutableListOf(
                BasicListItemWithImage(R.drawable.ic_pencil_grey600_24dp, context.getString(R.string.nc_promote)),
                BasicListItemWithImage(R.drawable.ic_pencil_grey600_24dp, context.getString(R.string.nc_demote)),
                BasicListItemWithImage(
                    R.drawable.ic_delete_grey600_24dp,
                    context.getString(R.string.nc_remove_participant)
                )
            )

            if (!conversation!!.canModerate(conversationUser)) {
                items = mutableListOf()
            } else {
                if (participant.type == Participant.ParticipantType.MODERATOR || participant.type == Participant.ParticipantType.OWNER) {
                    items.removeAt(0)
                } else if (participant.type == Participant.ParticipantType.USER) {
                    items.removeAt(1)
                }
            }

            if (items.isNotEmpty()) {
                MaterialDialog(activity!!, BottomSheet(WRAP_CONTENT)).show {
                    cornerRadius(res = R.dimen.corner_radius)

                    title(text = participant.displayName)
                    listItemsWithImage(items = items) { dialog, index, _ ->

                        val apiVersion = ApiUtils.getConversationApiVersion(conversationUser, intArrayOf(1))

                        if (index == 0) {
                            if (participant.type == Participant.ParticipantType.MODERATOR) {
                                ncApi.demoteModeratorToUser(
                                    credentials,
                                    ApiUtils.getUrlForRoomModerators(
                                        apiVersion,
                                        conversationUser.baseUrl,
                                        conversation!!.token
                                    ),
                                    participant.userId
                                )
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe {
                                        getListOfParticipants()
                                    }
                            } else if (participant.type == Participant.ParticipantType.USER) {
                                ncApi.promoteUserToModerator(
                                    credentials,
                                    ApiUtils.getUrlForRoomModerators(
                                        apiVersion,
                                        conversationUser.baseUrl,
                                        conversation!!.token
                                    ),
                                    participant.userId
                                )
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe {
                                        getListOfParticipants()
                                    }
                            }
                        } else if (index == 1) {
                            if (participant.type == Participant.ParticipantType.GUEST ||
                                participant.type == Participant.ParticipantType.USER_FOLLOWING_LINK
                            ) {
                                ncApi.removeParticipantFromConversation(
                                    credentials,
                                    ApiUtils.getUrlForRemovingParticipantFromConversation(
                                        conversationUser.baseUrl,
                                        conversation!!.token,
                                        true
                                    ),
                                    participant.sessionId
                                )
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe {
                                        getListOfParticipants()
                                    }
                            } else {
                                ncApi.removeParticipantFromConversation(
                                    credentials,
                                    ApiUtils.getUrlForRemovingParticipantFromConversation(
                                        conversationUser.baseUrl,
                                        conversation!!.token,
                                        false
                                    ),
                                    participant.userId
                                )
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe {
                                        getListOfParticipants()
                                        // get participants again
                                    }
                            }
                        }
                    }
                }
            }
        }

        return true
    }

    companion object {

        private const val ID_DELETE_CONVERSATION_DIALOG = 0
    }

    /**
     * Comparator for participants, sorts by online-status, moderator-status and display name.
     */
    class UserItemComparator : Comparator<UserItem> {
        override fun compare(left: UserItem, right: UserItem): Int {
            if (left.isOnline && !right.isOnline) {
                return -1
            } else if (!left.isOnline && right.isOnline) {
                return 1
            }

            val moderatorTypes = ArrayList<Participant.ParticipantType>()
            moderatorTypes.add(Participant.ParticipantType.MODERATOR)
            moderatorTypes.add(Participant.ParticipantType.OWNER)
            moderatorTypes.add(Participant.ParticipantType.GUEST_MODERATOR)

            if (moderatorTypes.contains(left.model.type) && !moderatorTypes.contains(right.model.type)) {
                return -1
            } else if (!moderatorTypes.contains(left.model.type) && moderatorTypes.contains(right.model.type)) {
                return 1
            }

            return left.model.displayName.toLowerCase(Locale.ROOT).compareTo(
                right.model.displayName.toLowerCase(Locale.ROOT)
            )
        }
    }
}