//
//  AuthorDetailsInteractor.swift
//  TheBlog
//
//  Created by Marcio Garcia on 07/06/20.
//  Copyright (c) 2020 Oxl Tech. All rights reserved.
//
//  This file was generated by the Clean Swift Xcode Templates so
//  you can apply clean architecture to your iOS and Mac projects,
//  see http://clean-swift.com
//

import UIKit
import Services

protocol AuthorDetailsBusinessLogic {
    func fetchAuthor()
    func fetchFirstPosts()
    func fetchNextPosts()
    func selectPost(_ post: Post?)
}

protocol AuthorDetailsDataStore {
    var author: Author? { get set }
    var selectedPost: Post? { get set }
}

class AuthorDetailsInteractor: AuthorDetailsBusinessLogic, AuthorDetailsDataStore {
  
    var presenter: AuthorDetailsPresentationLogic?
    var worker: AuthorDetailsWorkLogic
  
    var author: Author?
    var selectedPost: Post?
    var page = 0
    var postsFirstPage = 10
    var postsPerPage = 10

    // MARK: Object lifecycle
    
    init(presenter: AuthorDetailsPresentationLogic?, worker: AuthorDetailsWorkLogic) {
        self.presenter = presenter
        self.worker = worker
    }

    // MARK: Fetch data
    func fetchAuthor() {
        presenter?.presentAuthor(author)
    }

    func fetchFirstPosts() {
        page = 1
        performRequest(page: page, postsPerPage: postsFirstPage)
    }

    func fetchNextPosts() {
        page += 1
        performRequest(page: page, postsPerPage: postsPerPage)
    }

    func selectPost(_ post: Post?) {
        selectedPost = post
    }

    private func performRequest(page: Int, postsPerPage: Int?) {
        guard let author = self.author else {
            let error = NSError(domain: "Data", code: 999, userInfo: [NSLocalizedDescriptionKey : "No author selected"])
            presenter?.presentError(error)
            return
        }

        worker.requestPosts(authorId: author.id,
                            page: page,
                            postsPerPage: postsPerPage,
                            orderBy: PostsOrderBy.date,
                            direction: SortDirection.desc) { [weak self] posts, error in

            if let _error = error {
                self?.presenter?.presentError(_error)
                return
            }
            guard let posts = posts else { return }
            self?.presenter?.presentPosts(posts)
        }
    }
}
