//
//  DocumentSearchInteractor.swift
//  Particle-Box
//
//  Created by Ian on 4/4/18.
//  Copyright (c) 2018 jumplabs. 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 DocumentSearchInteractorInput
{
    func getDocuments(filter: BoxDocumentSearchFilter)
    func getDocument(key: String, filter: BoxDocumentSearchFilter)
    func deleteDocument(document: BoxDocument)
}

protocol DocumentSearchInteractorOutput
{
    func updateDataSource(documents: [BoxDocument])
    func createAlert(_ message: String)
    func deleteDocument(document: BoxDocument)
}

class DocumentSearchInteractor: DocumentSearchInteractorInput
{
    
    var output: DocumentSearchInteractorOutput!    
        
    // MARK: Business logic
    
    func getDocuments(filter: BoxDocumentSearchFilter) {
        BoxAPIService.shared.getDocuments(filter: filter) { (documents, error) in
            guard error == nil else {
                self.output.createAlert((error?.localizedDescription)!)
                return
            }
            
            if documents != nil {
                self.output.updateDataSource(documents: documents!)
            }
        }
    }
    
    func getDocument(key: String, filter: BoxDocumentSearchFilter) {
        BoxAPIService.shared.getDocument(key: key, filter: filter) { (document, error) in
            guard error == nil else {
                self.output.createAlert((error?.localizedDescription)!)
                return
            }
            
            if document != nil {
                self.output.updateDataSource(documents: [document!])
            }
        }
    }
    
    func deleteDocument(document: BoxDocument) {
        BoxAPIService.shared.deleteDocument(document: document) { (responseCode, error) in
            guard error == nil else {
                self.output.createAlert((error?.localizedDescription)!)
                return
            }
            
            if responseCode != nil {
                switch responseCode {
                case 204?:
                    self.output.deleteDocument(document: document)
                    break
                case 400?:
                    self.output.createAlert("Bad input parameter.")
                    break
                case 404?:
                    self.output.createAlert("No document exists for these criteria.")
                    break
                default:
                    break
                }
            }
        }
    }
    
    

}
