aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/net/lacolaco/smileessence/activity/ManageAccountsActivity.kt
blob: d53e94a712ed8dac6b8d5908c652ee71538a4e15 (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
package net.lacolaco.smileessence.activity

import android.app.Activity
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Process
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.BaseAdapter
import kotlinx.android.synthetic.main.layout_edit_list.*
import kotlinx.android.synthetic.main.list_item_account.view.*
import net.lacolaco.smileessence.Application
import net.lacolaco.smileessence.R
import net.lacolaco.smileessence.World
import net.lacolaco.smileessence.data.Account
import net.lacolaco.smileessence.data.ImageCache
import net.lacolaco.smileessence.logging.Logger
import net.lacolaco.smileessence.util.bg
import net.lacolaco.smileessence.util.launchUi
import net.lacolaco.smileessence.view.confirm
import java.util.*

class ManageAccountsActivity : Activity() {
    private val adapter by lazy { EditAccountsAdapter() }
    private lateinit var receivedIntent: Intent

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Save the received intent
        receivedIntent = Intent(intent)

        // Check if it is initiated from launcher
        if (android.os.Build.VERSION.SDK_INT >= 23 &&
                checkPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, Process.myPid(),
                        Process.myUid()) != PackageManager.PERMISSION_GRANTED)
            requestPermissions(arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION)

        // Skip this activity if app is already started
        if (Application.currentWorld != null && !intent.getBooleanExtra(INTENT_KEY_NOINIT, false)) {
            goToWorld(Application.currentWorld!!)
            return
        }

        setContentView(R.layout.layout_edit_list)

        listview_edit_list.adapter = adapter
        listview_edit_list.setOnItemClickListener { adapterView: AdapterView<*>, view1: View, i: Int, l: Long ->
            val account = adapter.getItem(i)
            goToWorld(Application.getWorld(account.id))
        }
        listview_edit_list.setOnItemLongClickListener { adapterView: AdapterView<*>, view1: View, i: Int, l: Long ->
            if (adapter.count > 1) {
                // remove account from application
                val account = adapter.getItem(i)
                confirm(R.string.dialog_confirm_clear_account, account.user.screenName) {
                    adapter.removeAt(i)
                    //Account.unregister(account.id)
                }
                true
            } else {
                Application.toast(R.string.notice_cant_remove_last_account)
                false
            }
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        receivedIntent = Intent(intent)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        when (requestCode) {
            REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION -> {
                if (grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // OK
                    val currentWorld = Application.currentWorld
                    if (currentWorld != null) {
                        goToWorld(currentWorld)
                    }
                } else {
                    Application.toast(R.string.notice_error_storage_permission)
                    // TODO: Kill Process?
                    finish()
                }
            }
        }
    }

    private fun goToWorld(world: World) {
        // Continue the existing MainActivity
        receivedIntent.component = ComponentName(this, MainActivity::class.java)
        receivedIntent.putExtra(MainActivity.KEY_ORIGINAL_DATA, receivedIntent.data)
        receivedIntent.putExtra(MainActivity.KEY_ORIGINAL_TYPE, receivedIntent.type)
        val intent = Intent(this, MainActivity::class.java)
        intent.data = Uri.parse("smileessence://mainactivity/?user_id=" + world.account.id)
        finish()
        world.mainActivityIntent = receivedIntent
        startActivity(intent)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        val add = menu.add(Menu.NONE, R.id.menu_edit_list_add, Menu.NONE, "")
        add.setIcon(android.R.drawable.ic_menu_add)
        add.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.menu_edit_list_add -> startActivityForResult(Intent(this, OAuthActivity::class.java), REQUEST_OAUTH)
            android.R.id.home -> safeFinish()
            else -> return super.onOptionsItemSelected(item)
        }
        return true
    }

    override fun onBackPressed() {
        safeFinish()
    }

    private fun safeFinish() {
        val currentWorld = Application.currentWorld
        if (currentWorld != null) {
            goToWorld(currentWorld)
        } else {
            setResult(Activity.RESULT_CANCELED)
            finish()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) = when (requestCode) {
        REQUEST_OAUTH -> receiveOAuth(requestCode, resultCode, data)
        else -> Logger.error("[BUG] unexpected activity result: reqCode=$requestCode, resCode=$resultCode")
    }

    private fun receiveOAuth(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK) {
            launchUi {
                data!!
                adapter.add(bg {
                    Account.register(
                            data.getStringExtra(OAuthActivity.KEY_TOKEN),
                            data.getStringExtra(OAuthActivity.KEY_TOKEN_SECRET),
                            data.getLongExtra(OAuthActivity.KEY_USER_ID, -1L),
                            data.getStringExtra(OAuthActivity.KEY_SCREEN_NAME))
                }.await())
            }
        } else {
            Logger.error(requestCode)
            Application.toast(R.string.notice_error_authenticate)
        }
    }

    private inner class EditAccountsAdapter : BaseAdapter() {
        private val accounts: MutableList<Account> = ArrayList(Account.all())

        override fun getCount(): Int = accounts.size

        override fun getItem(position: Int): Account = accounts[position]

        override fun getItemId(position: Int): Long = accounts[position].id

        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            val view = convertView ?: layoutInflater.inflate(R.layout.list_item_account, parent, false)
            val account = getItem(position)
            view.account_icon.setImageUrl(account.user.profileImageUrl, ImageCache.getImageLoader())
            view.account_text_view.text = "@" + account.user.screenName
            return view
        }

        fun add(account: Account): Int = if (!accounts.contains(account)) {
            accounts.add(account)
            notifyDataSetChanged()
            accounts.size - 1
        } else {
            accounts.indexOf(account)
        }

        fun removeAt(position: Int): Account? {
            val account = accounts.removeAt(position)
            notifyDataSetChanged()
            return account
        }
    }

    companion object {
        val INTENT_KEY_NOINIT = "noInit"
        private val REQUEST_OAUTH = 10
        private val REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION = 11

    }
}