package com.hosshan.android.salad.component.scene.login

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import com.hosshan.android.salad.R
import com.hosshan.android.salad.component.scene.top.TopActivity
import com.hosshan.android.salad.component.scene.top.createIntent
import com.hosshan.android.salad.ext.bindView
import com.hosshan.android.salad.ext.start
import com.hosshan.android.salad.manager.IntentManager
import com.jakewharton.rxbinding.view.clicks
import com.trello.rxlifecycle.FragmentLifecycleProvider
import com.trello.rxlifecycle.components.support.RxFragment
import com.trello.rxlifecycle.kotlin.bindToLifecycle
import rx.android.schedulers.AndroidSchedulers
import javax.inject.Inject
import kotlin.properties.Delegates

/**
 * LoginFragment
 */
class LoginFragment : RxFragment(), LoginView {

    companion object {}

    var button: Button by Delegates.notNull()

    @Inject
    internal lateinit var presenter: LoginPresenter

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        LoginComponent.Initializer.init(activity).inject(this)
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? =
            inflater?.inflate(R.layout.fragment_login, container, false)?.apply {
                button = bindView(R.id.login_button)
            }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        presenter.initialize(this)

        button.clicks()
                .flatMap { presenter.createAuthorizeUrl() }
                .observeOn(AndroidSchedulers.mainThread())
                .bindToLifecycle(this)
                .subscribe {
                    // GitHubのAuthorizeページに遷移
                    IntentManager.createBrowseIntent(it).start(activity)
                }
    }

    override fun provideLifecycle(): FragmentLifecycleProvider = this

    override fun onError(throwable: Throwable) {

    }

    fun onNewIntent(intent: Intent?) {
        intent?.let {
            presenter.onCallbackAuthorize(it)
        }
    }

    override fun onLogined() {
        TopActivity.createIntent(activity).start(activity)
        activity.finish()
    }
}
