aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/net/lacolaco/smileessence/view/dialog/UserDetailDialogFragment.kt
blob: 6692f8f9962502addfdce1e5dadf389c110ade3f (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
package net.lacolaco.smileessence.view.dialog

import android.os.Bundle
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.text.Html
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.omadahealth.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection
import kotlinx.android.synthetic.main.dialog_user_detail.*
import net.lacolaco.smileessence.R
import net.lacolaco.smileessence.activity.MainActivity
import net.lacolaco.smileessence.entity.Tweet
import net.lacolaco.smileessence.entity.User
import net.lacolaco.smileessence.twitter.*
import net.lacolaco.smileessence.util.SortedList
import net.lacolaco.smileessence.util.browse
import net.lacolaco.smileessence.util.launchUi
import net.lacolaco.smileessence.view.Partials
import net.lacolaco.smileessence.view.PopupMenu
import net.lacolaco.smileessence.view.confirm

class UserDetailDialogFragment : StackableDialogFragment() {
    private lateinit var user: User
    private var isFollowedByMe = false
    private var isFollowingMe = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val found = User.fetch(arguments.getLong(KEY_USER_ID))
        if (found == null) {
            world.notify(R.string.notice_error_show_user)
            dismiss()
            return
        }
        user = found
    }

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        imageview_user_detail_menu.setOnClickListener { showPopupMenu() }
        user_detail_screenname.setOnClickListener { browse(user.userHomeURL) }
        textview_user_detail_description.movementMethod = LinkMovementMethod.getInstance()
        textview_user_detail_tweet_count.setOnClickListener { browse(user.userHomeURL) }
        textview_user_detail_friend_count.setOnClickListener {
            browse(String.format("%s/following", user.userHomeURL))
        }
        textview_user_detail_follower_count.setOnClickListener {
            browse(String.format("%s/followers", user.userHomeURL))
        }
        textview_user_detail_favorite_count.setOnClickListener {
            browse(String.format("%s/favorites", user.userHomeURL))
        }
        user_detail_icon.setOnClickListener { browse(user.profileImageUrl) }
        user_detail_banner.setOnClickListener { user.profileBannerUrl?.let { browse(it) } }
        toggle_follow.setOnClickListener { toggleFollowing() }

        user_timeline.addItemDecoration(
                DividerItemDecoration(activity, DividerItemDecoration.VERTICAL))
        val lm = LinearLayoutManager(activity)
        lm.orientation = LinearLayoutManager.VERTICAL
        user_timeline.layoutManager = lm
        val adapter = UserTimelineAdapter()
        user_timeline.adapter = adapter

        val refreshLayout = user_detail_refresh_layout
        refreshLayout.setOnRefreshListener {
            launchUi {
                try {
                    if (it == SwipyRefreshLayoutDirection.TOP) {
                        val tweets = world.getUserTimelineAsync(user.id,
                                sinceId = adapter.getMaxIdOrNull()).await()
                        adapter.addAll(tweets)
                    } else {
                        val tweets = world.getUserTimelineAsync(user.id,
                                maxId = adapter.getMinIdMinusOneOrNull()).await()
                        adapter.addAll(tweets)
                    }
                } catch (e: TwitterTaskException) {
                    world.notifyError("Could not retrieve user timeline")
                }
                refreshLayout.isRefreshing = false
            }
        }

        updateRelationship()
        launchUi {
            try {
                val tweets = world.getUserTimelineAsync(user.id).await()
                adapter.addAll(tweets)
            } catch (e: TwitterTaskException) {
                world.notifyError("Could not retrieve user timeline")
            }
        }

        refreshViews()
    }

    private fun refreshViews() {
        Glide.with(this).load(user.profileImageUrl).into(user_detail_icon)
        Glide.with(this).load(user.profileBannerUrl).into(user_detail_banner)
        user_detail_name.text = user.name
        user_detail_screenname.text = "@${user.screenName}"
        user_protected_indicator.visibility = if (user.isProtected) View.VISIBLE else View.INVISIBLE


        user_detail_location.text = user.location
        user_detail_url.text = user.url
        textview_user_detail_description.text = Html.fromHtml(user.decoratedDescription)

        textview_user_detail_tweet_count.text = user.statusesCount.toString()
        textview_user_detail_friend_count.text = user.friendsCount.toString()
        textview_user_detail_follower_count.text = user.followersCount.toString()
        textview_user_detail_favorite_count.text = user.favoritesCount.toString()

        if (user === world.user) {
            toggle_follow.text = "This is you"
            toggle_follow.isEnabled = false
            textview_user_detail_followed.visibility = View.GONE
        } else {
            toggle_follow.isEnabled = true
            toggle_follow.isActivated = isFollowedByMe
            toggle_follow.text = if (isFollowedByMe) "Unfollow" else "Follow"
            textview_user_detail_followed.setText(
                    if (isFollowingMe) R.string.user_detail_followed
                    else R.string.user_detail_not_followed)
        }
    }

    private fun showPopupMenu() {
        val popup = PopupMenu(activity, imageview_user_detail_menu)
        popup.add(R.string.command_user_add_to_reply) {
            (activity as MainActivity).openPostPageAndReplyTo(user)
            world.notify(R.string.notice_add_to_reply)
        }
        popup.add(R.string.command_user_block) {
            confirm(R.string.dialog_confirm_commands) {
                launchUi {
                    try {
                        world.blockAsync(user.id).await()
                        world.notify(R.string.notice_block_succeeded)
                        updateRelationship()
                    } catch (e: TwitterTaskException) {
                        world.notifyError(R.string.notice_block_failed)
                    }
                }
            }
        }
        popup.add(R.string.command_user_unblock) {
            launchUi {
                try {
                    world.unblockAsync(user.id).await()
                    world.notify(R.string.notice_unblock_succeeded)
                    updateRelationship()
                } catch (e: TwitterTaskException) {
                    world.notifyError(R.string.notice_unblock_failed)
                }
            }
        }
        popup.add(R.string.command_user_r4s) {
            confirm(R.string.dialog_confirm_commands) {
                launchUi {
                    try {
                        world.reportSpamAsync(user.id).await()
                        world.notify(R.string.notice_r4s_succeeded)
                        updateRelationship()
                    } catch (e: TwitterTaskException) {
                        world.notifyError(R.string.notice_r4s_failed)
                    }
                }
            }
        }
        popup.show()
    }

    private fun toggleFollowing() {
        assert(toggle_follow.isEnabled)
        confirm(R.string.dialog_confirm_commands) {
            val isFollowing = toggle_follow.isActivated
            toggle_follow.isEnabled = false
            toggle_follow.text = "..."
            launchUi {
                try {
                    if (isFollowing) {
                        world.unfollowAsync(user.id).await()
                        world.notify(R.string.notice_unfollow_succeeded)
                    } else {
                        world.followAsync(user.id).await()
                        world.notify(R.string.notice_follow_succeeded)
                    }
                    updateRelationship()
                } catch (e: TwitterTaskException) {
                    world.notifyError(if (isFollowing)
                        R.string.notice_unfollow_failed
                    else
                        R.string.notice_follow_failed)
                }
            }
        }
    }

    private fun updateRelationship() {
        if (user !== world.user) {
            toggle_follow.isEnabled = false
            toggle_follow.text = "..."
            launchUi {
                textview_user_detail_followed.setText(R.string.user_detail_loading)
                try {
                    val relationship = world.getRelationshipAsync(user.id).await()
                    isFollowedByMe = relationship.isSourceFollowingTarget
                    isFollowingMe = relationship.isSourceFollowedByTarget
                } catch (e: TwitterTaskException) {
                    world.notifyError("Failed to fetch relationship")
                }
                refreshViews()
            }
        }
    }

    companion object {
        private const val KEY_USER_ID = "userID"

        fun newInstance(user: User): UserDetailDialogFragment {
            val obj = UserDetailDialogFragment()
            val bundle = Bundle()
            bundle.putLong(KEY_USER_ID, user.id)
            obj.arguments = bundle
            return obj
        }
    }

    private inner class UserTimelineAdapter :
            RecyclerView.Adapter<UserTimelineAdapter.ViewHolder>() {
        private val sortedList = SortedList<Tweet>(
                { position -> notifyItemInserted(position) },
                { position, count -> notifyItemRangeRemoved(position, count) }
        )

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            Partials.getTweetView(sortedList[position], world, activity, holder.itemView)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val layoutInflater = LayoutInflater.from(parent.context)
            return ViewHolder(layoutInflater.inflate(R.layout.list_item_tweet, parent, false))
        }

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

        fun addAll(items: Collection<Tweet>) {
            sortedList.addAll(items)
        }

        fun getMaxIdOrNull(): Long? {
            return if (sortedList.size > 0)
                sortedList[0].id
            else
                null
        }

        fun getMinIdMinusOneOrNull(): Long? {
            return if (sortedList.size > 0)
                sortedList[sortedList.size - 1].id - 1
            else
                null
        }

        private inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
    }
}