/*

Blitzortung.org lightning monitor android app
Copyright (C) 2012 - 2015 Andreas Würl

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

package org.blitzortung.android.v2

import android.app.Fragment
import android.os.Bundle

import org.blitzortung.android.data.result.Result
import org.slf4j.LoggerFactory

import rx.schedulers.Schedulers
import rx.subjects.BehaviorSubject

class StateFragment : Fragment() {

    interface OnCreateListener {
        fun onStateCreated(stateFragment: StateFragment)
    }

    var resultSubject: BehaviorSubject<Result?>? = null
        private set
    private var onCreateListener: OnCreateListener? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        LOGGER.info("StateFragment.onCreate()")
        super.onCreate(savedInstanceState)

        retainInstance = true

        resultSubject = BehaviorSubject.create<Result>()
        resultSubject!!.subscribeOn(Schedulers.newThread()).observeOn(Schedulers.newThread())
    }

    override fun onPause() {
        LOGGER.info("StateFragment.onPause()")
        super.onPause()

        onCreateListener = null
    }

    override fun onResume() {
        LOGGER.info("StateFragment.onResume()")
        super.onResume()

        if (onCreateListener != null) {
            LOGGER.info("StateFragment.onResume() call onCreateListener")
            onCreateListener!!.onStateCreated(this)
        }
    }

    override fun onDestroy() {
        LOGGER.debug("StateFragment.onDestroy()")
        super.onDestroy()

        resultSubject = null
    }

    fun setOnCreateListener(onCreateListener: OnCreateListener) {
        this.onCreateListener = onCreateListener
    }

    companion object {

        val TAG = StateFragment::class.java.getSimpleName()

        private val LOGGER = LoggerFactory.getLogger(StateFragment::class.java)
    }
}
