Newer
Older
OverlayMultiCounter / app / src / main / kotlin / jackall / overlaymulticounter / viewmodel / MainViewModel.kt
MatsumotoKeiju on 10 Nov 2017 5 KB [add] Activation of service
package jackall.overlaymulticounter.viewmodel

import android.app.Activity
import android.app.AlertDialog
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import android.content.DialogInterface
import android.content.Intent
import android.databinding.BindingAdapter
import android.net.Uri
import android.provider.Settings
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import io.realm.OrderedRealmCollectionChangeListener
import io.realm.RealmResults
import jackall.overlaymulticounter.App
import jackall.overlaymulticounter.CounterAdapter
import jackall.overlaymulticounter.R
import jackall.overlaymulticounter.contract.CounterContract
import jackall.overlaymulticounter.db.CounterRealmHelper
import jackall.overlaymulticounter.service.MainService
import jackall.overlaymulticounter.utils.RuntimePermissionUtil
import jackall.overlaymulticounter.utils.ServiceUtil
import jackall.overlaymulticounter.vo.Counter
import java.util.*

/**
 * Created by matsumoto_k on 2017/11/10.
 */
class MainViewModel : ViewModel(), LifecycleObserver, CounterContract {
    var counterAdapter: CounterAdapter
    var counterRealmHelper = CounterRealmHelper()
    var realmChangeListener: OrderedRealmCollectionChangeListener<RealmResults<Counter>>
    var results: RealmResults<Counter>

    init {
        val items = ArrayList<CounterItemViewModel>()
        results = counterRealmHelper.findAll()
        results.forEachIndexed { index, counter ->
            items.add(CounterItemViewModel(counter, this@MainViewModel as CounterContract))
        }
        counterAdapter = CounterAdapter(App.get(), items)
        realmChangeListener = OrderedRealmCollectionChangeListener { results, changeSet ->
            changeSet.insertions.forEach {
                counterAdapter.insert(CounterItemViewModel(results.get(it), this@MainViewModel as CounterContract))
            }
            changeSet.deletions.forEach {
                counterAdapter.remove(it)
            }
        }
        results.addChangeListener(realmChangeListener)
    }

    fun onClickStartService(view: View) {
        // TODO: RuntimePermissionの処理
        if (RuntimePermissionUtil.checkOverlayPermission(view.context)) {
            if (ServiceUtil.isMainServiceRunning(view.context)) {
                val intent = Intent(view.context, MainService::class.java)
                view.context.stopService(intent)
            } else {
                val intent = Intent(view.context, MainService::class.java)
                view.context.startService(intent)
            }
        } else {
            AlertDialog.Builder(view.context)
                    .setMessage("常駐機能を使用するには権限の許可が必要です。")
                    .setPositiveButton("設定", DialogInterface.OnClickListener { dialog, which ->
                        val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:jackall.overlaymulticounter"))
                        (view.context as Activity).startActivityForResult(intent, 0)
                    })
                    .setNegativeButton("許可しない", null)
                    .show()
        }
    }

    fun onClickClose(view: View) {
        (view.context as Activity).finish()
    }

    fun onClickAdd(view: View) {
        counterRealmHelper.insert(
                Counter(
                        id = counterRealmHelper.getNextId(),
                        title = "Counter${counterRealmHelper.getNextId()}",
                        count = 0
                )
        )
    }

    fun onClickRemove(view: View) {
        counterRealmHelper.removeLast()
    }

    fun onClickResetAll(view: View) {
        counterRealmHelper.resetAll()
    }

    override fun plus(id: Int) {
        counterRealmHelper.plus(id)
    }

    override fun minus(id: Int) {
        counterRealmHelper.minus(id)
    }

    override fun reset(id: Int) {
        counterRealmHelper.reset(id)
    }

    override fun editTitle(id: Int, title: String) {
        counterRealmHelper.updateTitle(id, title)
    }

    fun onDestory() {
        counterRealmHelper.close()
    }

    class Factory() : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            return MainViewModel() as T
        }
    }

    object Adapter {
        @JvmStatic
        @BindingAdapter("android:setCounterAdapter")
        fun setCounterAdapter(recyclerView: RecyclerView, counterAdapter: CounterAdapter?) {
            if (counterAdapter == null)
                return
            recyclerView.layoutManager = LinearLayoutManager(App.get())
            recyclerView.adapter = counterAdapter
            val dividerItemDecoration = DividerItemDecoration(recyclerView.context, LinearLayoutManager.VERTICAL)
            dividerItemDecoration.setDrawable(recyclerView.context.resources.getDrawable(R.drawable.divider))
            recyclerView.addItemDecoration(dividerItemDecoration)
        }
    }
}