package com.fk.fuckoffer.ui.field

import android.util.Log
import com.fk.fuckoffer.domain.interactor.IFieldInteractor
import com.fk.fuckoffer.domain.model.Field
import com.fk.fuckoffer.domain.repository.FoaasRepository
import com.fk.fuckoffer.ui.BasePresenter
import io.reactivex.android.schedulers.AndroidSchedulers
import javax.inject.Inject

/**
 * Awful presenter. Refactor it. This list of fields is nasty and whoever made it should feel bad. TODO
 * Created by fk on 23.10.17.
 */
class FieldFormPresenter @Inject constructor(
        private val foaasRepository: FoaasRepository,
        private val fieldInteractor: IFieldInteractor) : BasePresenter<FieldFormView>() {

    fun getOperation(operationName: String, fieldIndex: Int) {
        foaasRepository.getOperationByName(operationName)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSuccess { view?.displayFieldInfo(it.fields[fieldIndex], it.fields.size == fieldIndex+1) }
                .flatMap { fieldInteractor.getPreviousValues(it.fields[fieldIndex]) }
                .subscribe(
                        { view?.displaySuggestions(it) },
                        { Log.e("Field", it.message, it) })
    }

    fun inputField(field: Field, value: String, last: Boolean) {
        fieldInteractor.registerValue(field, value)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        { if (last) view?.gotoPreview() else view?.gotoNextField() },
                        { Log.e("Field", it.message, it) })
    }
}