import UIKit
import RxSwift
import RxCocoa
import RealmSwift
import AuthenticationServices
import PKHUD

class AuthController: UIViewController, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
    
    @IBOutlet weak var username: UITextField!
    @IBOutlet weak var password: UITextField!
    @IBOutlet weak var login: UIButton!
    @IBOutlet weak var signup: UIButton!
    @IBOutlet weak var appleSignIn: ASAuthorizationAppleIDButton!
    
    let bag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.appleSignIn.cornerRadius = 6

        let authValid = Observable.combineLatest(self.username.rx.text, self.password.rx.text) { name, pass -> Bool in
            guard let name = name, let pass = pass else { return false }
            return name.count >= 4 && pass.count >= 5
        }
        
        authValid.bind(to: self.login.rx.isEnabled).disposed(by: self.bag)
        authValid.bind(to: self.signup.rx.isEnabled).disposed(by: self.bag)
        
        if Settings.shared.user.email.count > 0 {
            self.username.text = Settings.shared.user.email
        }
    }
    
    @IBAction func loginTapped(_ sender: UIButton) {
        guard let email = self.username.text, let pass = self.password.text else { return }
        
        HUD.show(.progress)
        Api.login(email: email, password: pass)
            .observeOn(MainScheduler.instance)
            .subscribe(onSuccess: self.goToMainScreen(user:), onError: HUD.show(error:))
            .disposed(by: self.bag)
    }
    
    @IBAction func signupTapped(_ sender: UIButton) {
        guard let email = self.username.text, let pass = self.password.text else { return }
        
        HUD.show(.progress)
        Api.signUp(email: email, password: pass)
            .observeOn(MainScheduler.instance)
            .subscribe(onSuccess: self.goToMainScreen(user:), onError: HUD.show(error:))
            .disposed(by: self.bag)
    }
    
    @IBAction func appleSignInTapped(_ sender: ASAuthorizationAppleIDButton) {
        let appleIDProvider = ASAuthorizationAppleIDProvider()
        let request = appleIDProvider.createRequest()
        request.requestedScopes = [.email]
        
        let authorizationController = ASAuthorizationController(authorizationRequests: [request])
        authorizationController.delegate = self
        authorizationController.presentationContextProvider = self
        authorizationController.performRequests()
    }

    func goToMainScreen(user: User) {
        guard let realm = try? Realm() else {
            HUD.flash(.labeledError(title: nil, subtitle: "Database error"))
            return
        }
        
        HUD.hide()
        
        if user.email != Settings.shared.user.email {
            try? realm.write {
                realm.deleteAll()
            }
        }
        
        Settings.shared.user = user
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        self.view.window?.rootViewController = storyboard.instantiateViewController(identifier: "MainSplitController")
    }
    
    // MARK: - Apple SignIn
    
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return self.view.window!
    }
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        switch authorization.credential {
        case let appleIDCredential as ASAuthorizationAppleIDCredential:
            guard let email = appleIDCredential.email else {
                HUD.flash(.labeledError(title: nil, subtitle: "Cannot get email"))
                return
            }
            
            HUD.show(.progress)
            Api.signIn(email: email, password: appleIDCredential.user)
                .observeOn(MainScheduler.instance)
                .subscribe(onSuccess: self.goToMainScreen(user:), onError: HUD.show(error:))
                .disposed(by: self.bag)
            
            if let tokenData = appleIDCredential.identityToken {
                let token = String(data: tokenData, encoding: .utf8) ?? ""
                _ = Api.fbVerifyAssertion(provider: "apple.com", idToken: token).subscribe(onSuccess: { _ in
                    print("")
                }, onError:  { error in
                    print(error)
                })
            }
        default:
            HUD.flash(.labeledError(title: nil, subtitle: "Unsupported authorization credential"))
            break
        }
    }
}
