package bou.amine.apps.readerforselfossv2.android

import android.content.Context
import androidx.annotation.ArrayRes
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.replaceText
import androidx.test.espresso.action.ViewActions.typeTextIntoFocusedView
import androidx.test.espresso.assertion.ViewAssertions.doesNotExist
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isChecked
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 org.hamcrest.CoreMatchers.allOf

fun performLogin(someUrl: String? = null) {
    onView(withId(R.id.urlView)).perform(click()).perform(
        typeTextIntoFocusedView(
            if (!someUrl.isNullOrEmpty()) someUrl else "http://10.0.2.2:8888"
        )
    )
    onView(withId(R.id.signInButton)).perform(click())
    Thread.sleep(10000)
}

fun loginAndInitHome() {

    performLogin()
    onView(withText(R.string.gdpr_dialog_title)).check(matches(isDisplayed()))
    onView(withText("OK")).perform(click())
}

fun changeAndCancelSetting(oldValue: String, newValue: String, openSettingItem: () -> Unit) {
    openSettingItem()
    onView(
        withId(android.R.id.edit)
    ).perform(replaceText(newValue))
    onView(
        withId(android.R.id.button2)
    ).perform(click())
    openSettingItem()
    onView(
        withId(android.R.id.edit)
    ).check(matches(withText(oldValue)))
    onView(
        withText(newValue)
    ).check(doesNotExist())
    onView(
        withId(android.R.id.button2)
    ).perform(click())
}

fun changeAndSaveSetting(oldValue: String, newValue: String, openSettingItem: () -> Unit) {
    openSettingItem()
    onView(
        withId(android.R.id.edit)
    ).perform(replaceText(newValue))
    onView(
        withId(android.R.id.button1)
    ).perform(click())
    openSettingItem()
    onView(
        withId(android.R.id.edit)
    ).check(matches(withText(newValue)))
    if (oldValue.isNotEmpty()) {
        onView(
            withText(oldValue)
        ).check(doesNotExist())
    }
    onView(
        withId(android.R.id.button2)
    ).perform(click())
}

fun testPreferencesFromArray(
    context: Context,
    @ArrayRes arrayRes: Int,
    openSettingItem: () -> Unit
) {
    openSettingItem()
    context.resources.getStringArray(arrayRes).forEach { res ->
        onView(withText(res)).check(matches(allOf(isDisplayed(), isNotChecked())))
        onView(withText(res)).perform(click())
        onView(withText(res)).check(doesNotExist())
        openSettingItem()
        onView(withText(res)).check(matches(allOf(isDisplayed(), isChecked())))
    }
}