package guepardoapps.passwordsafe.views.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import es.dmoral.toasty.Toasty
import guepardoapps.passwordsafe.R
import guepardoapps.passwordsafe.services.client.IClientService
import guepardoapps.passwordsafe.views.listener.OnLoginListener
import kotlinx.android.synthetic.main.fragment_login.*

internal class FragmentLogin : BaseFragment() {

    private lateinit var onLoginListener: OnLoginListener

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_login, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        fragment_login_button.setOnClickListener {
            val passphrase = fragment_login_input_passphrase.text.toString()

            if (passphrase.isNotEmpty()) {
                val loginResult = clientService.applicationLogin(passphrase)
                // If first is true, the passphrase is valid and user can login
                if (loginResult.successful) {
                    onLoginListener.loginSuccessful(passphrase)
                } else {
                    if (loginResult.maxInvalidReached) {
                        onLoginListener.loginFailed(true)
                    } else {
                        Toasty
                                .error(context!!, "Invalid passphrase (${loginResult.invalidCount} invalid tries!)", Toast.LENGTH_LONG)
                                .show()
                    }
                }
            } else {
                Toasty
                        .info(context!!, "Please provide a valid passphrase!)", Toast.LENGTH_LONG)
                        .show()
            }
        }
    }

    fun setup(clientService: IClientService, onLoginListener: OnLoginListener) {
        this.clientService = clientService
        this.onLoginListener = onLoginListener
    }
}