aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/net/lacolaco/smileessence/view/page/SearchFragment.kt
blob: d24a562c1973398ab76fe74640433cdf5390e01a (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
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2012-2014 lacolaco.net
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package net.lacolaco.smileessence.view.page

import android.app.AlertDialog
import android.os.Bundle
import android.text.Spannable
import android.text.TextUtils
import android.text.method.ArrowKeyMovementMethod
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.ListView
import android.widget.TextView
import com.handmark.pulltorefresh.library.PullToRefreshBase
import com.handmark.pulltorefresh.library.PullToRefreshListView
import kotlinx.android.synthetic.main.fragment_search.*
import net.lacolaco.smileessence.R
import net.lacolaco.smileessence.activity.MainActivity
import net.lacolaco.smileessence.preference.UserPreferenceHelper
import net.lacolaco.smileessence.twitter.task.Searches
import net.lacolaco.smileessence.util.SystemServiceHelper
import net.lacolaco.smileessence.util.UIHandler
import net.lacolaco.smileessence.view.adapter.TimelineAdapter
import net.lacolaco.smileessence.view.dialog.ConfirmDialogFragment
import twitter4j.Query

import java.util.ArrayList

class SearchFragment : CustomListFragment<TimelineAdapter>(), View.OnClickListener, View.OnLongClickListener, View.OnFocusChangeListener {
    override val adapter by lazy { TimelineAdapter(activity, world) }
    private lateinit var queryString: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
        queryString = UserPreferenceHelper.instance.get(R.string.key_last_used_search_query, "")
    }

    override fun refresh() { //TODO
        if (!TextUtils.isEmpty(queryString)) {
            startSearch(queryString)
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.button_search_queries -> {
                openSearchQueryDialog()
            }
            R.id.button_search_execute -> {
                search()
            }
            R.id.button_search_save -> {
                saveQuery()
            }
        }
    }

    override fun onLongClick(v: View): Boolean {
        when (v.id) {
            R.id.button_search_save -> {
                val text = edittext_search.text.toString()
                for (ss in world.savedSearches.values) {
                    if (ss.query == text) {
                        ConfirmDialogFragment.show(activity, getString(R.string.dialog_confirm_delete_query), {
                            Searches.DestroySavedSearchTask(world.account, ss.id)
                                    .onDoneUI { x ->
                                        world.notify(R.string.notice_search_query_deleted)
                                        world.refreshSavedSearches()
                                    }
                                    .onFailUI { x -> world.notify("unable to delete search query") }
                                    .execute()
                        }, false)
                        break
                    }
                }
                return true
            }
        }
        return false
    }

    override fun onFocusChange(v: View, hasFocus: Boolean) {
        if (!hasFocus) {
            SystemServiceHelper.hideIM(activity, edittext_search)
        }
    }
    override val refreshMode: PullToRefreshBase.Mode
        get() = PullToRefreshBase.Mode.BOTH

    override fun onPullDownToRefresh(refreshView: PullToRefreshBase<ListView>) {
        if (TextUtils.isEmpty(queryString)) {
            UIHandler().post {
                notifyTextEmpty()
                refreshView.onRefreshComplete()
            }
            return
        }
        val query = Query()
        query.query = queryString
        query.count = 200
        query.resultType = Query.RECENT
        if (adapter.count > 0) {
            query.sinceId = adapter.topID
        }
        runRefreshTask(query) {
            updateListViewWithNotice(refreshView.refreshableView, true)
            refreshView.onRefreshComplete()
        }
    }

    override fun onPullUpToRefresh(refreshView: PullToRefreshBase<ListView>) {
        if (TextUtils.isEmpty(queryString)) {
            UIHandler().post {
                notifyTextEmpty()
                refreshView.onRefreshComplete()
            }
            return
        }
        val query = Query()
        query.query = queryString
        query.count = 200
        query.resultType = Query.RECENT
        if (adapter.count > 0) {
            query.maxId = adapter.lastID - 1
        }
        runRefreshTask(query) {
            updateListViewWithNotice(refreshView.refreshableView, false)
            refreshView.onRefreshComplete()
        }
    }

    override fun getListView(page: View): PullToRefreshListView {
        return listview_search
    }

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

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        listview_search.setAdapter(adapter)
        listview_search.setOnScrollListener(this)
        listview_search.setOnRefreshListener(this)
        listview_search.mode = refreshMode
        button_search_queries.setOnClickListener(this)
        button_search_execute.setOnClickListener(this)
        button_search_save.setOnClickListener(this)
        edittext_search.onFocusChangeListener = this
        edittext_search.setText(queryString)
        edittext_search.setOnEditorActionListener { textView, i, keyEvent ->
            if (i == EditorInfo.IME_ACTION_SEARCH || keyEvent != null &&
                    keyEvent.action == KeyEvent.ACTION_DOWN &&
                    keyEvent.keyCode == KeyEvent.KEYCODE_ENTER) {
                search()
            }
            true
        }
        edittext_search.movementMethod = object : ArrowKeyMovementMethod() {
            override fun right(widget: TextView, buffer: Spannable): Boolean {
                //Don't move page
                return widget.selectionEnd == widget.length() || super.right(widget, buffer)
            }

            override fun left(widget: TextView, buffer: Spannable): Boolean {
                //Don't move page
                return widget.selectionStart == 0 || super.left(widget, buffer)
            }
        }

        refresh()
    }

    private fun notifyTextEmpty() {
        world.notifyError(R.string.notice_search_text_empty)
    }

    private fun openSearchQueryDialog() {
        val sss = ArrayList(world.savedSearches.values)
        val builder = AlertDialog.Builder(activity)
        builder.setItems(sss.map { it.query }.toTypedArray()) { dialog, which ->
            val ss = sss[which]
            (activity as MainActivity).openSearchPage(ss.query)
        }
        val dialog = builder.create()
        dialog.show()
    }

    private fun saveQuery() {
        val text = edittext_search.text.toString()
        if (TextUtils.isEmpty(text)) {
            world.notifyError(R.string.notice_query_is_empty)
        } else {
            Searches.CreateSavedSearchTask(world.account, text).onDoneUI { cb ->
                world.notify(R.string.notice_query_saved)
                world.refreshSavedSearches()
            }.onFailUI { ex -> world.notifyError("Query is not saved") }.execute()
        }
    }

    private fun search() {
        val text = edittext_search.text.toString()
        if (TextUtils.isEmpty(text)) {
            world.notifyError(R.string.notice_query_is_empty)
        } else {
            startSearch(text)
            SystemServiceHelper.hideIM(activity, edittext_search)
        }

    }

    fun startSearch(queryString: String) {
        UserPreferenceHelper.instance.set(R.string.key_last_used_search_query, queryString)
        edittext_search.setText(queryString)
        this.queryString = queryString
        adapter.clear()
        adapter.updateForce()
        if (!TextUtils.isEmpty(queryString)) {
            val query = Query()
            query.query = queryString
            query.count = 200
            query.resultType = Query.RECENT
            runRefreshTask(query) { adapter.updateForce() }
        }
    }

    private fun runRefreshTask(query: Query, onFinish: () -> Unit) {
        Searches.SearchTask(world.account, query)
                .onFail { x -> world.notifyError(R.string.notice_error_search) }
                .onDone { tweets -> adapter.addAll(tweets.filter { t -> !t.isRetweet }) }
                .onFinishUI(onFinish)
                .execute()
    }
}