//
//  LWHomeVC.swift



import UIKit
import AVFoundation
import PhotosUI
import Photos
import SSSpinnerButton
import WidgetKit
import GoogleMobileAds

class LWHomeVC: BaseViewController{

    //MARK:- Outlet
    @IBOutlet weak var viewTest: UIView!
    @IBOutlet var lblBadged: UILabel!
    @IBOutlet var viewCamaraContainer: UIView!
    @IBOutlet var viewCapturedPicToolbar: UIView!
    @IBOutlet var viewCamaraToolbar: UIView!
    @IBOutlet var viewSentBtn: UIView!
    @IBOutlet var viewCamaraCapture: UIView!
    @IBOutlet var viewOrImg: UIView!
    @IBOutlet var viewGradient: GradientView!
    @IBOutlet var sendBtn: SSSpinnerButton!
    @IBOutlet var cameraImageView: UIImageView!
    @IBOutlet var btnImagePicker: UIButton!
    @IBOutlet var viewSheet: UIView!
    @IBOutlet var lblBottomSheet: UILabel!
    @IBOutlet var btnFlash: UIButton!
    @IBOutlet weak var imgFlash: UIImageView!
    @IBOutlet var btnSaveImage: UIButton!
    @IBOutlet weak var bannerView: GADBannerView!
    @IBOutlet weak var imgSendOnBtn: UIButton!
    @IBOutlet weak var imgDownloadBtn: UIImageView!
    @IBOutlet weak var btnSendHeight: NSLayoutConstraint!
    @IBOutlet weak var sendBtnImageHeight: NSLayoutConstraint!
    
    @IBOutlet weak var btnAccountsAdd: UIButton!
    @IBOutlet weak var btnMenu: UIButton!
    @IBOutlet weak var btnClosefriendList: UIButton!
    
    
    //MARK:- Variable
    var capturePhotoOutput: AVCapturePhotoOutput?
    var imagePicker = UIImagePickerController()
    var cameraManager = CameraManager()
    var isPhotoCaptured = false
    var isFriendAvailable = false
    var homeViewModel = HomeViewModel()
    var capturedImage = UIImage()
    var mInterstitial: GADInterstitialAd!
    var addFriendViewModel = AddFriendViewModel()
    //MARK:- Life Cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initWithData()
        updateWidget()
        setupCameraView()
        showHideView(isCaptured: false)
        getImageFromLibrary()
        checkForceUpdate()
        handleNotificationObserver()
        if FIRRemoteManagement.shared.isShowBannerAds && Reachability.isInternetAvailable{
            showBannerViewAds()
        }
        
        if DeviceType.ISPAD {
            viewGradient.layer.cornerRadius = btnSendHeight.constant / 2
            imgSendOnBtn.layer.cornerRadius = sendBtnImageHeight.constant / 2
            btnMenu.setButtonIcon()
            btnAccountsAdd.setButtonIcon()
            btnClosefriendList.setButtonIcon()
            btnFlash.setButtonIcon()
            btnSaveImage.setButtonIcon()
            cameraManager.shouldRespondToOrientationChanges = false
        }
        
        
    }
    override func viewWillAppear(_ animated: Bool) {
        self.checkFriendList()
        self.openAddFriendViewFromNotification(notification:nil)
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
    
    override func viewWillLayoutSubviews(){
        setUpUI()
    }
    
    //MARK:- Init Function
    func requestCameraAuthentication(completion : @escaping (Bool) -> ()){
        
        let status = AVCaptureDevice.authorizationStatus(for: .video)
        
        switch status {
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { (success) in
                if success{
                    completion(success)
                }
                else{
                    completion(success)
                }
            }
        case .restricted:
            completion(false)
        case .denied:
            completion(false)
        case .authorized:
            completion(true)
        @unknown default:
            fatalError()
        }
    }
    
    func showBannerViewAds(){
        bannerView.adUnitID = AdvertisementIds.Banner
        bannerView.rootViewController = self
        bannerView.load(GADRequest())
    }
    
    func setupCameraView(){
        self.requestCameraAuthentication { (success) in
            DispatchQueue.main.async {
                if success { // if request is granted (success is true)
                    APPDEL.regiserForRemoteNotification()
                    self.cameraManager.addPreviewLayerToView(self.viewCamaraContainer, newCameraOutputMode: CameraOutputMode.stillImage)
                }
                else{
                    APPDEL.regiserForRemoteNotification()
                }
            }
        }
    }
    
    func showHideView(isCaptured : Bool){
        
        self.viewCamaraCapture.isHidden = isCaptured
        self.viewSentBtn.isHidden = !isCaptured
        self.viewOrImg.isHidden = !isCaptured
        
        self.viewCamaraToolbar.isHidden = isCaptured
        self.viewCapturedPicToolbar.isHidden = !isCaptured
    }
    
    func initWithData(){}
    func updateWidget(){
        WidgetCenter.shared.reloadAllTimelines()
    }
    func setUpUI(){
        self.viewSheet.roundCorners([.topLeft,.topRight], radius: 25)
    }
    

    
    func requestPhotoAuthentication(success : @escaping (Bool) -> ()){
        
        let status = PHPhotoLibrary.authorizationStatus()
        
        switch status {
            
        case .notDetermined:
            PHPhotoLibrary.requestAuthorization{ status in
                if status == .authorized{
                    success(true)
                }
                else{
                    success(false)
                }
            }
        case .restricted:
            success(false)
        case .denied:
            success(false)
        case .authorized:
            success(true)
        case .limited:
            success(true)
        @unknown default:
            fatalError()
        }
    }
    
    func presentPhotoPicker(){
        DispatchQueue.main.async {
            if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
                debugPrint("Button capture")
                
                self.imagePicker.delegate = self
                self.imagePicker.sourceType = .savedPhotosAlbum
//                self.imagePicker.allowsEditing = true
                self.imagePicker.allowsEditing = false
                
                self.present(self.imagePicker, animated: true, completion: nil)
            }
        }
    }
    
    
    //MARK: - Add image to Library -
        @objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
            if let error = error {
                debugPrint(error)
            } else {

            }
        }
    
    func showPhotoDeniedAlert(){
        
        let alertView = UIAlertController(title: Alert_Message.PhotoPermissionTitle, message: Alert_Message.PhotoPermissionDiscription, preferredStyle: .alert)

        let gotoSetting = UIAlertAction(title: Alert_Message.OpenSettings, style: .default, handler: { (action) -> Void in
            UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
        })

        let cancel = UIAlertAction(title: Alert_Message.Cancel, style: .cancel) { (action) -> Void in
            
        }

        alertView.addAction(gotoSetting)
        alertView.addAction(cancel)

        self.present(alertView, animated: true, completion: nil)
    }
    
    func showCameraDeniedAlert(){
        
        let alertView = UIAlertController(title: Alert_Message.CameraPermissionTitle, message: Alert_Message.CameraPermissionDiscription, preferredStyle: .alert)

        let gotoSetting = UIAlertAction(title: Alert_Message.OpenSettings, style: .default, handler: { (action) -> Void in
            UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
        })

        let cancel = UIAlertAction(title: Alert_Message.Cancel, style: .cancel) { (action) -> Void in
            
        }

        alertView.addAction(gotoSetting)
        alertView.addAction(cancel)

        self.present(alertView, animated: true, completion: nil)
    }
    
    func getImageFromLibrary(){
        let status = PHPhotoLibrary.authorizationStatus()
        
        switch status {
            
        case .notDetermined:
            print("notDetermined")
        case .restricted:
            print("restricted")
        case .denied:
            print("denied")
        case .authorized:
            self.fetchLatestImageFromLibrary()
        case .limited:
            self.fetchLatestImageFromLibrary()
        @unknown default:
            fatalError()
        }        
    }
    
    func fetchLatestImageFromLibrary(){
        DispatchQueue.main.async {
            UIImage().fetchLastSavedPhotos(view: self.view) { image in
                self.btnImagePicker.setImage(image, for: .normal)
            } failure: { error in
                debugPrint("Error:", error)
            }
        }
    }
    
    func getLastSentFriendId() -> String{
        var arrIds = [String]()
        for data in self.homeViewModel.arrLastSentFriend.value{
            arrIds.append(String(data.friend_id ?? 0))
        }
        return arrIds.joined(separator: ",")
    }
    
    func captureImageFromCamera(){
        let settings = AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.jpeg])
        self.capturePhotoOutput?.capturePhoto(with: settings, delegate: self)
        showHideView(isCaptured: true)
        self.lblBottomSheet.text = "Pick Friends"
        self.isPhotoCaptured = true
        switch cameraManager.cameraOutputMode {
        case .stillImage:
            cameraManager.capturePictureWithCompletion { result in
                switch result {
                case .failure:
                    self.cameraManager.showErrorBlock("Error occurred", "Cannot save picture.")
                case .success(let content):
                    if let capturedData = content.asData {
                        
                        self.capturedImage = UIImage(data: capturedData)!
                        
                        let fllipedImage = UIImage(cgImage: (self.capturedImage.cgImage)!, scale: self.capturedImage.scale, orientation: .leftMirrored)
                        self.cameraImageView.image = self.cameraManager.cameraDevice == CameraDevice.front ? fllipedImage :  self.capturedImage
                        self.cameraImageView.contentMode = .scaleAspectFill
                        self.cameraImageView.isHidden = false
                        self.viewCamaraContainer.isHidden = true
                    }
                }
            }
        case .videoWithMic, .videoOnly:
            break
        }
    }
    
    private func handleNotificationObserver(){
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.openAddFriendViewFromNotification(notification:)), name: Notification.Name.ReceivePushNotification, object: nil)
        
        NotificationCenter.default.addObserver(self,selector: #selector(handleEnterForeground),name: UIApplication.willEnterForegroundNotification, object: nil)
    }
    
    @objc func handleEnterForeground(){
        self.checkForceUpdate()
        WidgetCenter.shared.reloadAllTimelines()
    }
    
    func checkForceUpdate(){
        if FIRRemoteManagement.shared.isForceAppUpdate{
            do{
                let isUpdateAvailable = try APPDEL.isUpdateAvailable()
                if isUpdateAvailable{
                    APPDEL.showForceUpdateAlert(alertText: FIRRemoteManagement.shared.isForceAppUpdateDescription)
                }
            }catch{
                print(error)
            }
        }
    }
    
    @objc func openAddFriendViewFromNotification(notification: Notification?){
        NotificatioManager.shared.redirectToSpecificVC()
    }
    
    func checkFriendList(){
        APIDataManager.shared.getFriendListAPI { success in
            if success.count != 0{
                self.isFriendAvailable = true
            }
            else{
                self.isFriendAvailable = false
            }
        } failure: { (error) in
            debugPrint("Error Occured",error)
        }
    }
    
    //MARK: - Button Action -        
    @IBAction func sendBtnTapped(_ sender: Any) {
        self.sendBtn.startAnimate(spinnerType: SpinnerType.ballSpinFade, spinnercolor: UIColor.black, spinnerSize: 30, complete: nil)
        
        if Reachability.isInternetAvailable{
            self.homeViewModel.getLastSentFriendList { response in
                if response.count != 0{
//                    let img = UIImage.init(data: self.capturedImage.jpegData(compressionQuality: 0.3) ?? Data())
                    self.homeViewModel.callSendImageAPI(friendIds: self.getLastSentFriendId(), image: self.capturedImage) { success in
                        if success{
                            self.sendBtn.stopAnimate(complete: nil)
                            self.viewCamaraContainer.isHidden = false
                            self.cameraImageView.isHidden = true
                            
                            self.showHideView(isCaptured: false)
                            self.isPhotoCaptured = false
                            self.lblBottomSheet.text = "History"
                            if FIRRemoteManagement.shared.isShowInterstitialAds && Reachability.isInternetAvailable{
                                AdvertiseManager.sharedInstance.delegateFullScreen = self
                                AdvertiseManager.sharedInstance.showInterstitialAd()
                            }                                             
                        }
                    }
                }
                else{
                    self.sendBtn.stopAnimate(complete: nil)
                    ScreenManager.shared.moveToPickFriendVC(capturedImage: self.capturedImage, isFromHistory: false, imageId: Int(self.getLastSentFriendId())) { isPhotoSent in
                        self.viewCamaraContainer.isHidden = false
                        self.cameraImageView.isHidden = true
                        
                        self.showHideView(isCaptured: false)
                        self.isPhotoCaptured = false
                        self.lblBottomSheet.text = "History"
                    }
                }
            }
        }
        else{
            Utilities.showAlertView(nil, Alert_Message.networkAlertMsg) { value in
                self.sendBtn.stopAnimate(complete: nil)
            }
        }
    }
    
    @IBAction func captureBtnTapped(_ sender: Any) {
                
        self.requestCameraAuthentication { success in
            if success{
                if Reachability.isInternetAvailable{
                    if self.isFriendAvailable{
                        self.captureImageFromCamera()
                    }
                    else{
                        self.showAlertViewWithCancelBtn(Alert_Message.friendAlertDesc, Alert_Message.friendAlertTitle, defaultTitle: Alert_Message.addFriend, cancelTitle: Alert_Message.Ok) { value in
                            if value {
                                ScreenManager.shared.moveToAddFriendVC(selectedTab: 0)
                            }
                        }
                    }
                }
                else{
                    self.showAlertView(nil, Alert_Message.networkAlertMsg) { _ in}
                }
            }
            else{
                self.showCameraDeniedAlert()
            }
        }
        
        
        
        if FIRRemoteManagement.shared.isShow_NativeReviewPopup{
            var nativeReviewCount = FIRRemoteManagement.shared.nativeReviewCount
            //Update count
            UserDefaultManager.shared.captureCount += 1
            
            //Open Native review popup
            if UserDefaultManager.shared.captureCount % nativeReviewCount == 0 {
                debugPrint("Review Capture Count = \(UserDefaultManager.shared.captureCount)")
                ScreenManager.shared.showNativeReviewPopup()
            }
        }
        
//        if UserDefaultManager.shared.isHideCustomReview == false && FIRRemoteManagement.shared.isShow_CustomReviewPopup == false{
//         
//            //Update count
//            UserDefaultManager.shared.captureCount += 1
//            
//            //Open custom review popup
//            if UserDefaultManager.shared.captureCount % RatingPopupCnt.captureCnt == 0{
//                debugPrint("Review Capture Count = \(UserDefaultManager.shared.captureCount)")
//                ScreenManager.shared.moveToCustomRating()
//            }
//        }
    }
    
    @IBAction func accountBtnTapped(_ sender: Any) {
        ScreenManagerShared.moveToAddFriendVC(selectedTab: 0)
    }
    
    @IBAction func settingBtnTapped(_ sender: Any) {
        ScreenManagerShared.moveToSettingVC()
    }
    @IBAction func flashBtnTapped(_ sender: Any) {
        switch cameraManager.changeFlashMode() {
        case .off:
            // self.btnFlash.setImage(UIImage(named: "flash_off"), for: .normal)
            self.imgFlash.image = UIImage(named: "flash_off")
        case .on:
            // self.btnFlash.setImage(UIImage(named: "flash_icon"), for: .normal)
            self.imgFlash.image = UIImage(named: "flash_icon")
        case .auto:
           // self.btnFlash.setImage(UIImage(named: "flash_auto"), for: .normal)
            self.imgFlash.image = UIImage(named: "flash_auto")
        }
    }
    @IBAction func closeBtnTapped(_ sender: Any) {
        
        self.viewCamaraContainer.isHidden = false
        self.cameraImageView.isHidden = true
        
        showHideView(isCaptured: false)
        self.isPhotoCaptured = false
        self.lblBottomSheet.text = "History"
        self.sendBtn.stopAnimate(complete: nil)
    }
    @IBAction func saveBtnTapped(_ sender: Any) {
        
        self.requestPhotoAuthentication { (success) in
            if success{
                guard let selectedImage = self.cameraImageView.image else {return}
                UIImageWriteToSavedPhotosAlbum(selectedImage, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
                self.fetchLatestImageFromLibrary()
                UIView.animate(withDuration: 1.0) {
                    self.btnSaveImage.setImage(UIImage(systemName: "checkmark.circle"), for: .normal)
                }
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                    UIView.animate(withDuration: 1.0) {
                        self.btnSaveImage.setImage(UIImage(named: "download_icon"), for: .normal)
                    }
                }
            }
            else{
                self.showPhotoDeniedAlert()
            }
        }
    }
    
    @IBAction func changeCameraBtnTapped(_ sender: Any) {
        
        self.cameraManager.cameraDevice = self.cameraManager.cameraDevice == CameraDevice.front ? CameraDevice.back : CameraDevice.front
        
//        if FIRRemoteManagement.shared.isShow_NativeReviewPopup{
//            ScreenManager.shared.showNativeReviewPopup()
//        }
    }
    
    @IBAction func imagePickerBtnTapped(_ sender: Any) {
        
        self.requestPhotoAuthentication { (success) in
            if success{
                
                if self.isFriendAvailable{
                    DispatchQueue.main.async {
                        self.presentPhotoPicker()
                        self.fetchLatestImageFromLibrary()
                    }
                }
                else{
                    DispatchQueue.main.async {
                        self.showAlertViewWithCancelBtn(Alert_Message.friendAlertDesc, Alert_Message.friendAlertTitle, defaultTitle: Alert_Message.addFriend, cancelTitle: Alert_Message.Ok) { value in
                            if value {
                                ScreenManager.shared.moveToAddFriendVC(selectedTab: 0)
                            }
                        }
                    }
                }
            }
            else{
                DispatchQueue.main.async {
                    self.showPhotoDeniedAlert()
                }
            }
        }
    }
    
    @IBAction func btnPresentHistoryTapped(_ sender: Any) {
        
        if self.isPhotoCaptured{
            ScreenManager.shared.moveToPickFriendVC(capturedImage: self.capturedImage, isFromHistory: false, imageId: nil) { isPhotoSent in
                self.viewCamaraContainer.isHidden = false
                self.cameraImageView.isHidden = true
                
                self.showHideView(isCaptured: false)
                self.isPhotoCaptured = false
                self.lblBottomSheet.text = "History"
            }
        }
        else{
            ScreenManager.shared.showHistoryVC()
        }
    }
}

extension LWHomeVC : AVCapturePhotoCaptureDelegate, AVCaptureMetadataOutputObjectsDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[.originalImage] as? UIImage{
            
            self.isPhotoCaptured = true
            self.capturedImage = image
            self.lblBottomSheet.text = "Pick Friends"
            self.cameraImageView.image = image
            self.cameraImageView.contentMode = .scaleAspectFill
            self.cameraImageView.isHidden = false
            self.viewCamaraContainer.isHidden = true
            self.showHideView(isCaptured: true)
            
            self.dismiss(animated: true) {
                if UserDefaultManager.shared.isHideCustomReview == false && FIRRemoteManagement.shared.isShow_CustomReviewPopup{
                    
                    //Update the count
                    UserDefaultManager.shared.photoPickerCount += 1
                    
                    
                    //Show Custom Review Popup
                    if UserDefaultManager.shared.photoPickerCount % RatingPopupCnt.photoPickerCnt == 0 {
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                         //   ScreenManager.shared.moveToCustomRating()
                            debugPrint("Review Photo Picker Count = \(UserDefaultManager.shared.photoPickerCount)")
                        }
                    }
                }
            }
        }
    }
}

extension LWHomeVC:FullScreenAdDelegate{
    func handleAdvertiseCallBack(isPresented: Bool, errMsg: String, adType: AdvertiseType) {
        if isPresented {
            APPDEL.isOpenInterstitialAds = true
        debugPrint("\(NSStringFromClass(Swift.type(of: self))) ::: Interestitial Ad Present")
        }
        else {
            APPDEL.isOpenInterstitialAds = false
            debugPrint("\(NSStringFromClass(Swift.type(of: self))) ::: Interestitial Ad Error = \(errMsg)")
        }
    }
    
    func willPresentFullScreenAd(adType: AdvertiseType) {
        print(adType)
    }
    
    func didDismissFullScreenAd(adType: AdvertiseType) {
       APPDEL.isOpenInterstitialAds = false
    }
    
}

