Newer
Older
MonCalc / app / src / main / kotlin / jackall / moncalc / viewmodel / TempleAnalyzeViewModel.kt
package jackall.moncalc.viewmodel

import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import android.databinding.BindingAdapter
import android.databinding.ObservableField
import android.graphics.Color
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import com.github.mikephil.charting.charts.PieChart
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.formatter.IValueFormatter
import com.github.mikephil.charting.utils.ViewPortHandler
import io.reactivex.schedulers.Schedulers
import jackall.moncalc.App
import jackall.moncalc.R
import jackall.moncalc.adapter.AnalyzeTempleAdapter
import jackall.moncalc.common.Notification
import jackall.moncalc.db.MonstDataRealmHelper
import jackall.moncalc.db.QuestRecordRealmHelper
import jackall.moncalc.model.PieChartModel
import jackall.moncalc.utils.RxBus
import jackall.moncalc.vo.Temple
import kotlin.concurrent.thread


/**
 * Created by matsumoto_k on 2017/11/04.
 */
class TempleAnalyzeViewModel : LifecycleViewModel() {

    val baseTempleName by lazy { App.instance.resources.getStringArray(R.array.base_temple_name) }
    val pieData = ObservableField<PieData>()
    val pieChartModel = ObservableField<PieChartModel>()
    val items = ObservableField<ArrayList<TempleAnalyzeItemViewModel>>()

    init {
        thread {
            setTempleAnalyzeList()
            setTempleAnalyzePie()
        }
        RxBus.observe<Notification>().observeOn(Schedulers.newThread()).subscribe {
            when (it.name) {
                Notification.DATACHANGED.name -> {
                    thread {
                        setTempleAnalyzeList()
                        setTempleAnalyzePie()
                    }
                }
            }
        }
    }

    fun setTempleAnalyzeList() {
        val questRealmHelper = QuestRecordRealmHelper()
        val monstDataRealmHelper = MonstDataRealmHelper()
        val items = ArrayList<TempleAnalyzeItemViewModel>()
        val specialPercent = questRealmHelper.getAllSpecialPercent()
        items.add(
                TempleAnalyzeItemViewModel(
                        "総合",
                        questRealmHelper.findAll().size.toString(),
                        "${if (specialPercent.isNaN()) 0 else String.format("%.1f", specialPercent)}%"
                )
        )

        monstDataRealmHelper.findAll(Temple::class.java).forEach {
            val count = questRealmHelper.countById(it.id)
            if (count == 0)
                return@forEach
            items.add(
                    TempleAnalyzeItemViewModel(
                            monstDataRealmHelper.findNameById(Temple::class.java, it.id),
                            count.toString(),
                            "${String.format("%.1f", questRealmHelper.getSpecialPercent(it.id))}%"
                    )
            )
        }
        this.items.set(items.apply { sortByDescending { it.count() } })
        questRealmHelper.close()
        monstDataRealmHelper.close()
    }

    fun setTempleAnalyzePie() {
        val questRealmHelper = QuestRecordRealmHelper()
        val entries = ArrayList<PieEntry>()
        for (attribute in 0..4) {
            val count = questRealmHelper.countByAttribute(attribute)
            if (count > 0) {
                entries.add(PieEntry(count.toFloat(), baseTempleName.get(attribute)))
            }
        }
        pieChartModel.set(PieChartModel(entries.apply { sortByDescending { it.value } }, ""))
        this.pieData.set(pieChartModel.get().pieData)
        questRealmHelper.close()
    }

    object Adapter {
        @JvmStatic
        @BindingAdapter("android:pieChart")
        fun hoge(mChart: PieChart, pieData: PieData?) {
            if (pieData == null)
                return
            val start = System.currentTimeMillis()
            mChart.setEntryLabelColor(Color.BLACK)
            mChart.isDrawHoleEnabled = false
            mChart.legend.verticalAlignment = Legend.LegendVerticalAlignment.TOP
            mChart.legend.horizontalAlignment = Legend.LegendHorizontalAlignment.RIGHT
            mChart.legend.orientation = Legend.LegendOrientation.VERTICAL
            mChart.isRotationEnabled = false
            pieData.setValueFormatter(object : IValueFormatter {
                override fun getFormattedValue(value: Float, entry: Entry?, dataSetIndex: Int, viewPortHandler: ViewPortHandler?): String {
                    return String.format("%.0f", value)
                }
            })
            mChart.description.text = "神殿周回割合"
            mChart.data = pieData
            mChart.invalidate()
        }

        @JvmStatic
        @BindingAdapter("android:setAnalyzeTempleList")
        fun setAnalyzeTempleList(view: RecyclerView, items: ArrayList<TempleAnalyzeItemViewModel>?) {
            if (items == null)
                return
            view.layoutManager = LinearLayoutManager(App.instance)
            view.adapter = AnalyzeTempleAdapter(App.instance, items)
            view.adapter.notifyDataSetChanged()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }

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