import UIKit
import WowonderMessengerSDK
import CoreLocation
import Contacts
import AVFoundation
import Photos

class IntroVC: UIViewController, UIScrollViewDelegate {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var NextButton: UIButton!
    @IBOutlet weak var skipBtn: UIButton!
    @IBOutlet weak var scrollNextBtn: UIButton!
    @IBOutlet weak var pageControl: UIPageControl!
    @IBOutlet weak var scrollView: UIScrollView! {
        didSet {
            self.scrollView.delegate = self
        }
    }
    
    // MARK: - Properties
    
    var slides: [IntroItem] = []
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setepUI()
    }
    
    // MARK: - Helper Functions
    
    func setepUI() {
        slides = createSlides()
        setupSlideScrollView(slides: slides)
        pageControl.numberOfPages = slides.count
        pageControl.currentPage = 0
        view.bringSubviewToFront(pageControl)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            self.locationPermisstion()
        }
    }
    
    func locationPermisstion() {
        let locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.requestAlwaysAuthorization()
    }
    
    func contactsPermission() {
        let contactStore = CNContactStore()
        let authorizationStatus = CNContactStore.authorizationStatus(for: .contacts)
        switch authorizationStatus {
        case .notDetermined:
            // Request access if authorization status is not determined
            contactStore.requestAccess(for: .contacts) { (granted, error) in
                if granted {
                    // Access granted, perform necessary operations
                } else {
                    // Access denied, handle the error or show an alert
                }
            }
        case .authorized:
            break
            // Access already granted, perform necessary operations
        case .denied, .restricted:
            break
            // Access denied or restricted, handle the error or show an alert
        case .limited:
            break
        }
    }
    
    func recordingPermisstion() {
        AVAudioSession.sharedInstance().requestRecordPermission { (granted) in
            if granted {
                // Permission granted, perform necessary operations
            } else {
                // Permission denied, handle the error or show an alert
            }
        }
    }
    
    func photoPermisstion() {
        PHPhotoLibrary.requestAuthorization { status in
            switch status {
            case .authorized:
                // Permission granted, perform necessary operations
                break
            case .denied, .restricted:
                // Permission denied or restricted, handle the error or show an alert
                break
            case .notDetermined:
                // Shouldn't happen, but handle it anyway
                break
            case .limited:
                // The user has authorized limited access to their photos
                // Handle the limited access accordingly
                break
            }
        }
    }
    
    @IBAction func NextButtonTapped(_ sender: UIButton) {
        let newVC = R.storyboard.dashboard.tabBarNav()
        appDelegate.window?.rootViewController = newVC
    }
    
    @IBAction func skipPressed(_ sender: Any) {
        let newVC = R.storyboard.dashboard.tabBarNav()
        appDelegate.window?.rootViewController = newVC
    }
    
    @IBAction func moveToNextPressed(_ sender: Any) {
        if scrollNextBtn.titleLabel?.text == NSLocalizedString("Done", comment: ""){
            let newVC = R.storyboard.dashboard.tabBarNav()
            appDelegate.window?.rootViewController = newVC
        } else {
            scrollToNextSlide()
            if pageControl.currentPage == 0 {
                self.contactsPermission()
            } else if pageControl.currentPage == 1 {
                self.recordingPermisstion()
            } else if pageControl.currentPage == 2 {
                self.photoPermisstion()
            }
        }
    }
    
    private func createSlides() -> [IntroItem] {
        
        let slide1: IntroItem = Bundle.main.loadNibNamed("IntroItemView", owner: self, options: nil)?.first as! IntroItem
        slide1.imageLabel.image = UIImage(named: "IntroImage")?.withRenderingMode(.alwaysOriginal)
        slide1.imageLabel.tintColor = UIColor.accent
        slide1.firstLabel.text = NSLocalizedString("Set your location", comment: "")
        slide1.secondLabel.text =  NSLocalizedString("Set your location so we can tell you where the nearest intresting people are, Discover friends near by.", comment: "")
        
        let slide2:IntroItem = Bundle.main.loadNibNamed("IntroItemView", owner: self, options: nil)?.first as! IntroItem
        slide2.imageLabel.image = UIImage(named: "GroupChat")?.withRenderingMode(.alwaysOriginal)
        slide2.imageLabel.tintColor = UIColor.accent
        slide2.firstLabel.text = NSLocalizedString("Make Group chat", comment: "")
        slide2.secondLabel.text = NSLocalizedString("You are getting boared? start and create a new group and add your friends and contacts and share all your posts from one place.", comment: "")
        
        let slide3:IntroItem = Bundle.main.loadNibNamed("IntroItemView", owner: self, options: nil)?.first as! IntroItem
        slide3.imageLabel.image = UIImage(named: "RecordingAccess")?.withRenderingMode(.alwaysOriginal)
        slide3.imageLabel.tintColor = UIColor.accent
        slide3.firstLabel.text = NSLocalizedString("Recording Access", comment: "")
        slide3.secondLabel.text = NSLocalizedString("Grant us the permission to allow your app to leave voice notes and recorded songs on your news feed comments.", comment: "")
        
        let slide4:IntroItem = Bundle.main.loadNibNamed("IntroItemView", owner: self, options: nil)?.first as! IntroItem
        slide4.imageLabel.image = UIImage(named: "MultimediaFiles")?.withRenderingMode(.alwaysOriginal)
        slide4.imageLabel.tintColor = UIColor.accent
        slide4.firstLabel.text = NSLocalizedString("Multimedia Files", comment: "")
        slide4.secondLabel.text = NSLocalizedString("Post all kind of images & stickers & videos & document files on your own news feed.", comment: "")
        
        return [slide1, slide2, slide3, slide4]
    }
    
    private func setupSlideScrollView(slides : [IntroItem]) {
        scrollView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
        scrollView.contentSize = CGSize(width: view.frame.width * CGFloat(slides.count), height: view.frame.height)
        scrollView.isPagingEnabled = true
        for i in 0 ..< slides.count {
            slides[i].frame = CGRect(x: view.frame.width * CGFloat(i), y: 0, width: view.frame.width, height: view.frame.height)
            scrollView.addSubview(slides[i])
        }
    }
    
    func scrollToNextSlide() {
        let cellSize = CGSize(width: self.view.frame.width, height: self.view.frame.height)
        let contentOffset = scrollView.contentOffset;
        scrollView.scrollRectToVisible(CGRect(x: contentOffset.x + cellSize.width, y: contentOffset.y, width: cellSize.width, height: cellSize.height), animated: true);
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y > 0 || scrollView.contentOffset.y < 0 {
            scrollView.contentOffset.y = 0
        }
        let pageIndex = round(scrollView.contentOffset.x/view.frame.width)
        pageControl.currentPage = Int(pageIndex)
        if pageControl.currentPage == 3 {
            self.skipBtn.isHidden = true
            NextButton.isHidden = false
            scrollNextBtn.isHidden = true
            self.NextButton.setTitle(NSLocalizedString("Get Started", comment: ""), for: .normal)
            //self.scrollNextBtn.setTitle(NSLocalizedString("Done", comment: ""), for: .normal)
        } else {
            self.skipBtn.isHidden = false
            NextButton.isHidden = true
            scrollNextBtn.isHidden = false
            self.scrollNextBtn.setTitle("Next", for: .normal)
        }
    }
    
}

// MARK: - Extensions

// MARK: CLLocationManagerDelegate Methods
extension IntroVC: CLLocationManagerDelegate {
    
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedAlways {
            if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) {
                if CLLocationManager.isRangingAvailable() {
                    // do stuff
                }
            }
        }
    }
    
}
