/*
 * Copyright (c) 2021 PSMForums. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.joshuacerdenia.android.nicefeed.util

/*  This object generates variations of a base URL to be used for requesting a feed,
    in case the original URL doesn't work the first time.
*/
object BackupUrlManager {

    private const val COUNTER_MAX = 4
    private var attemptCount = 0
        get() = if (field > COUNTER_MAX) 0 else field

    private var url: String? = null // Base URL
    private var urlPlusFeed: String? = null
    private var urlPlusRss: String? = null
    private var urlPlusRssXml: String? = null

    fun setBase(url: String?) {
        attemptCount = 0
        this.url = url
        if (url != null) {
            urlPlusFeed = "$url/feed"
            urlPlusRss = "$url/rss"
            urlPlusRssXml = "$url/rss.xml"
            // Expandable to other possible suffixes, just increase max count
        } else resetValues()
    }

    fun getNextUrl(): String? {
        attemptCount += 1
        return when (attemptCount - 1) {
            0 -> url
            1 -> urlPlusFeed
            2 -> urlPlusRss
            3 -> urlPlusRssXml
            else -> {
                setBase(null)
                null
            }
        }
    }

    fun reset() {
        setBase(null)
    }

    private fun resetValues() {
        urlPlusFeed = null
        urlPlusRss = null
        urlPlusRssXml = null
    }
}