//
//  KQLoginInteractor.swift
//  TaskProjectDemo
//
//  Created by Apple on 10/30/19.
//  Copyright (c) 2019 Apple. 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 KQLoginBusinessLogic
{
    func loginRequest(request: KQLogin.Api.Request)
    func loginAction()
    func skipAction()
}

protocol KQLoginDataStore
{
  var user: User? { get set}
}

class KQLoginInteractor: KQLoginBusinessLogic, KQLoginDataStore
{
    var user: User?
    var presenter: KQLoginPresentationLogic?
    var worker: KQLoginWorker?
    var userBusiness = UserBusiness()

    // MARK: loginRequest

    func loginRequest(request: KQLogin.Api.Request)
    {
        worker = KQLoginWorker()

        if let valid = worker?.validateInputs(request: request){
            let email = request.email
            let password = request.password
            let params = ["email": "testios@gmail.com",
                          "password": "12345678"]
            self.userLogin(parameters: params) { (loginModel, error) in
                guard let loginModel = loginModel else {return}
                var response : KQLogin.Api.Response = KQLogin.Api.Response(success: true, message:
                    "",userLogin:loginModel)
                guard let result = loginModel.result?.values else {return}
                guard let serverUser = result.first else {return}
                guard let userId = serverUser.id else {return}
                guard let token = serverUser.token else {return}
                Defaults.save("\(userId)", authToken: token)
                self.user = User(serverUser: serverUser, completed: true)
                print(self.user)
                self.presenter?.displayOnScreen(response: response)
            }
        }
    }

    func loginAction() {
        self.presenter?.presentHome()
    }

    func skipAction() {
         self.presenter?.presentHome()
    }
    
    func userLogin(parameters: [String : Any],completion:@escaping((_ loginModel:LoginModel?,_ error:Error?) -> ())){
        userBusiness.login(parameters: parameters) { (LoginModel, error) in
            if error == nil{
                self.presenter?.presentHome()
                completion(LoginModel,error)
               // print(LoginModel?.result)
            } else if let error = error as? NetworkError {
                completion(nil,error)
                print(error.message)
            } else if let error = error as? ServiceError {
                completion(nil,error)
                print(error.httpStatus, error.httpStatus)
            } else if let error = error as? UnknownParseError {
                completion(nil,error)
                print(error.localizedDescription)
            }
        }
    }
}
