package bou.amine.apps.readerforselfossv2.android

import android.app.Activity
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.IdlingRegistry
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isClickable
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.isNotChecked
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import bou.amine.apps.readerforselfossv2.android.testing.CountingIdlingResourceSingleton
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
@LargeTest
class LoginActivityTest {

    @get:Rule
    val activityRule = ActivityScenarioRule(LoginActivity::class.java)

    private fun getActivity(): Activity? {
        var activity: Activity? = null
        activityRule.scenario.onActivity {
            activity = it
        }
        return activity
    }

    @Before
    fun registerIdlingResource() {
        IdlingRegistry.getInstance()
            .register(CountingIdlingResourceSingleton.countingIdlingResource)
    }

    @After
    fun unregisterIdlingResource() {
        IdlingRegistry.getInstance()
            .unregister(CountingIdlingResourceSingleton.countingIdlingResource)
    }

    @Test
    fun viewIsInitialized() {
        onView(withId(R.id.urlView)).check(matches(isDisplayed()))
        onView(withId(R.id.selfSigned)).check(matches(isDisplayed())).check(matches(isNotChecked()))
            .check(
                matches(isClickable())
            )
        onView(withId(R.id.withLogin)).check(matches(isDisplayed()))
            .check(matches(isNotChecked())).check(
                matches(isClickable())
            )
    }

    @Test
    fun urlError() {
        performLogin("172.17.0.1:8888")
        onView(withId(R.id.urlView)).perform(click())
        onView(withId(R.id.urlView)).check(matches(withError(R.string.wrong_infos)))
    }

    @Test
    fun multiError() {
        onView(withId(R.id.signInButton)).perform(click())
        onView(withId(R.id.signInButton)).perform(click())
        onView(withId(R.id.signInButton)).perform(click())
        onView(withText(R.string.warning_wrong_url)).check(matches(isDisplayed()))
    }

    @Test
    fun connect() {
        performLogin()
        onView(withText(R.string.gdpr_dialog_title)).check(matches(isDisplayed()))
    }
}