//
//  HomePresenter.swift
//  TVShows
//
//  Created by Filip Gulan on 29/07/2018.
//  Copyright (c) 2018 Filip Gulan. All rights reserved.
//
//  This file was generated by the 🐍 VIPER generator
//

import UIKit
import RxSwift
import RxCocoa

final class HomePresenter {

    // MARK: - Private properties -

    private unowned let view: HomeViewInterface
    private let interactor: HomeInteractorInterface
    private let wireframe: HomeWireframeInterface
    private let _disposeBag = DisposeBag()

    // MARK: - Lifecycle -

    init(view: HomeViewInterface, interactor: HomeInteractorInterface, wireframe: HomeWireframeInterface) {
        self.view = view
        self.interactor = interactor
        self.wireframe = wireframe
    }
}

// MARK: - Extensions -

extension HomePresenter: HomePresenterInterface {

    func setup(with output: Home.ViewOutput) -> Home.ViewInput {
        output
            .logoutPressed
            .drive(onNext: { [unowned wireframe] in
                wireframe.pop()
            })
            .disposed(by: _disposeBag)
    
        let items = interactor
            .loadShows()
            .handleLoadingAndError(with: wireframe)
            .map { [unowned self] shows -> [CollectionCellItem] in
                return self.setupItems(shows)
            }
            .asDriverOnErrorComplete()

        let itemsReloader = output
            .refresh
            .startWith(()) // Manually invoke call at start
            .flatMapLatest { items }
        
        return Home.ViewInput(items: itemsReloader)
    }
}

private extension HomePresenter {
    
    func setupItems(_ shows: [Show]) -> [CollectionCellItem] {
        let items = shows.map { show -> ShowCollectionCellItem in
            var imageUrl: URL? = nil
            if let imageId = show.imageUrl {
                imageUrl = URL(string: "https://api.infinum.academy" + imageId)
            }
            let item = ShowCollectionCellItem(title: show.title, imageUrl: imageUrl) { [unowned wireframe] in
                wireframe.navigate(to: .showDetails(showId: show.id))
            }
            return item
        }
        return items
    }
}

