package com.example.myapplication.api.repository

import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadType
import androidx.paging.PagingState
import androidx.paging.RemoteMediator
import androidx.room.withTransaction
import com.example.myapplication.api.MyServerService
import com.example.myapplication.api.model.toProduct
import com.example.myapplication.database.AppDb
import com.example.myapplication.database.entities.Product
import com.example.myapplication.database.entities.RemoteKeyType
import com.example.myapplication.database.entities.RemoteKeys
import com.example.myapplication.database.repository.OfflineProductRepository
import com.example.myapplication.database.repository.OfflineRemoteKeyRepository
import retrofit2.HttpException
import java.io.IOException

@OptIn(ExperimentalPagingApi::class)
class ProductRemoteMediator(
    private val service: MyServerService,
    private val dbProductRepository: OfflineProductRepository,
    private val dbRemoteKeyRepository: OfflineRemoteKeyRepository,
    private val categoryRestRepository: RestCategoryRepository,
    private val database: AppDb
) : RemoteMediator<Int, Product>() {

    override suspend fun initialize(): InitializeAction {
        return InitializeAction.LAUNCH_INITIAL_REFRESH
    }

    override suspend fun load(
        loadType: LoadType,
        state: PagingState<Int, Product>
    ): MediatorResult {
        val page = when (loadType) {
            LoadType.REFRESH -> {
                val remoteKeys = getRemoteKeyClosestToCurrentPosition(state)
                remoteKeys?.nextKey?.minus(1) ?: 1
            }

            LoadType.PREPEND -> {
                val remoteKeys = getRemoteKeyForFirstProduct(state)
                remoteKeys?.prevKey
                    ?: return MediatorResult.Success(endOfPaginationReached = remoteKeys != null)
            }

            LoadType.APPEND -> {
                val remoteKeys = getRemoteKeyForLastProduct(state)
                remoteKeys?.nextKey
                    ?: return MediatorResult.Success(endOfPaginationReached = remoteKeys != null)
            }
        }

        try {
            val products = service.getProducts(page, state.config.pageSize)
            val endOfPaginationReached = products.isEmpty()
            database.withTransaction {
                if (loadType == LoadType.REFRESH) {
                    dbRemoteKeyRepository.deleteRemoteKey(RemoteKeyType.ITEM)
                    dbProductRepository.clearProducts()
                }
                val prevKey = if (page == 1) null else page - 1
                val nextKey = if (endOfPaginationReached) null else page + 1
                val keys = products.map {
                    RemoteKeys(
                        entityId = it.id,
                        type = RemoteKeyType.ITEM,
                        prevKey = prevKey,
                        nextKey = nextKey
                    )
                }
                categoryRestRepository.getAll()
                dbRemoteKeyRepository.createRemoteKeys(keys)
                dbProductRepository.insertAll(products.map { it.toProduct() })
            }
            return MediatorResult.Success(endOfPaginationReached = endOfPaginationReached)
        } catch (exception: IOException) {
            return MediatorResult.Error(exception)
        } catch (exception: HttpException) {
            return MediatorResult.Error(exception)
        }
    }

    private suspend fun getRemoteKeyForLastProduct(state: PagingState<Int, Product>): RemoteKeys? {
        return state.pages.lastOrNull { it.data.isNotEmpty() }?.data?.lastOrNull()
            ?.let { item ->
                dbRemoteKeyRepository.getAllRemoteKeys(item.productId!!, RemoteKeyType.ITEM)
            }
    }

    private suspend fun getRemoteKeyForFirstProduct(state: PagingState<Int, Product>): RemoteKeys? {
        return state.pages.firstOrNull { it.data.isNotEmpty() }?.data?.firstOrNull()
            ?.let { item ->
                dbRemoteKeyRepository.getAllRemoteKeys(item.productId!!, RemoteKeyType.ITEM)
            }
    }
    private suspend fun getRemoteKeyClosestToCurrentPosition(
        state: PagingState<Int, Product>
    ): RemoteKeys? {
        return state.anchorPosition?.let { position ->
            state.closestItemToPosition(position)?.productId?.let { itemUid ->
                dbRemoteKeyRepository.getAllRemoteKeys(itemUid, RemoteKeyType.ITEM)
            }
        }
    }

}