//
//  MainInteractor.swift
//  JSONPlaceHolderApp
//
//  Created by Iván Díaz Molina on 15/2/21.
//  Copyright (c) 2021 IDIAZM. 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

protocol MainBusinessLogic {
    func setupView()
    
    // MARK: Posts
    func didSelectedItemAt(index: Int)
    func getPostsCount() -> Int
    func getPostCellFor(index: Int) -> Main.Models.PostCellModel
}

protocol MainDataStore {
    var posts: [Post]? { get set }
    var selectedPost: Post? { get set }
}

class MainInteractor: MainBusinessLogic, MainDataStore {
    
    var presenter: MainPresentationLogic?
    var worker: MainWorker?
    var posts: [Post]?
    var selectedPost: Post?
    
    // MARK: Business Logic
    
    func setupView() {
        
        worker = MainWorker()
        
        let response = Main.SetupView.Response()
        presenter?.setupView(response: response)
        
        getInitialData()
    }
    
    /// method selects a post from specific index
    /// - Parameter index: index
    func didSelectedItemAt(index: Int) {
        
        guard let post = posts?.getElement(index) else { return }
        
        selectedPost = post
        
        
        worker?.selectPost(post: post)
        
        
        let response = Main.DidSelectedItem.Response(post: selectedPost)
        
        presenter?.presentPostDetails(response: response)
    }
    
    /// return the posts count
    /// - Returns: count
    func getPostsCount() -> Int {
        return posts?.count ?? 0
    }
    
    /// method returns the cellModel for current index
    /// - Parameter index: index
    /// - Returns: cell model
    func getPostCellFor(index: Int) -> Main.Models.PostCellModel {
        guard let post = posts?.getElement(index) else { return Main.Models.PostCellModel() }
        
        return Main.Models.PostCellModel(post: post)
    }
    
    /// method fetchs the initial data for the app
    fileprivate func getInitialData() {
        
        presenter?.displayLoading(true)
        
        let deadlineTime = DispatchTime.now() + 1
        DispatchQueue.main.asyncAfter(deadline: deadlineTime) { [weak self] in
            
            self?.worker?.getPosts(completion: { (posts, error) in
                                
                self?.posts = posts
                
                self?.presenter?.displayLoading(false)
                self?.presenter?.presentPosts()
            })
        }
    }
}
