//
//  ViewController.swift
//  CapturePhotoApp
//
//  Created by CS23 on 09/08/17.
//  Copyright © 2017 cearsinfotech. All rights reserved.
//
import UIKit
import PinterestLayout
import Stripe
class ViewController: UIViewController ,UICollectionViewDelegate , UICollectionViewDataSource , PinterestLayoutDelegate , UIGestureRecognizerDelegate{
    @IBOutlet var MainView: UIView!
    @IBOutlet var LightHeaderView: UIView!
    @IBOutlet var LightHeaderWidth: NSLayoutConstraint!
    @IBOutlet var lblHeaderTitle: UILabel!
    var isAppfirst : Bool = false
    var isscrolling : Bool = true
    var Isopen : Bool = true
    var Globaltimer: Timer?
    @IBOutlet var TutorialView: UIView!
    var ismoredata : Bool = false
    var IsFinish = false
    var pageCount = 1
    var pageSize = 30
    var orderType : String = ""
    var lastcellindex : Int = 1
    var DownloadiMage : UIImageView = UIImageView()
    @IBOutlet var GotITWidth: NSLayoutConstraint!
    @IBOutlet var btnTutorialgotit: UIButton!
    @IBOutlet var ImageCollectionview: UICollectionView!
    var arr_img : NSMutableArray = NSMutableArray()
    var arr_responseObject : NSMutableArray = NSMutableArray()
    var swipeRight : UISwipeGestureRecognizer?
    var swipeleft : UISwipeGestureRecognizer?
    @IBAction func btn_got_it(_ sender: Any) {
        UserDefaults.standard.set(true, forKey: "isFirstView")
        UserDefaults.standard.synchronize()
        TutorialView.isHidden = true
        self.LightHeaderView.alpha = 1.0
        UIView.animate(withDuration: 5.0, animations: {
            self.LightHeaderView.alpha = 0.0
            self.view.layoutIfNeeded()
        })
    }
    var manager = AFHTTPSessionManager()
    //MARK:- view life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        if let isfirst = UserDefaults.standard.object(forKey: "isFirstView") as? Bool {
            isAppfirst = isfirst
            TutorialView.isHidden = true
            GIFProgressHUD .show(withGIFName: "loader", addedTo: self.view, animated: true)
        }
        else{
            TutorialView.isHidden = false
        }
        btnTutorialgotit.layer.cornerRadius = btnTutorialgotit.frame.size.height / 2
        btnTutorialgotit.clipsToBounds = true
        LightHeaderView.layer.cornerRadius = LightHeaderView.frame.size.height / 2
        LightHeaderView.clipsToBounds = true
        LightHeaderView.alpha = 0.0
        orderType = "New"
        lblHeaderTitle.text = orderType.uppercased()
        if UIDevice.current.userInterfaceIdiom == .pad{
            ImageCollectionview.scrollPointsPerSecond = 70.0
            LightHeaderWidth.constant = 300
            GotITWidth.constant = 286
        }else{
            if UIScreen.main.bounds.width == 375
            {
                 GotITWidth.constant = 230
                ImageCollectionview.scrollPointsPerSecond = 70.0
                LightHeaderWidth.constant = 180
            }
            else if UIScreen.main.bounds.width == 414
            {
                 GotITWidth.constant = 286
                ImageCollectionview.scrollPointsPerSecond = 90.0
                LightHeaderWidth.constant = 200
            }
            else{
               ImageCollectionview.scrollPointsPerSecond = 70.0
            }
        }
        let layout = PinterestLayout()
        ImageCollectionview.collectionViewLayout = layout
        layout.delegate = self
        layout.cellPadding = 3
        layout.numberOfColumns = 3
        self.callWebserviceAuthorize(pageindex: pageCount, Pagesize: pageSize)
        self.ImageCollectionview.addInfiniteScrolling {
            if !self.IsFinish{
                self.pageCount += 1
                self.callWebserviceAuthorize(pageindex: self.pageCount, Pagesize: self.pageSize)
            }
        }
        //pushProductView
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.methodOfReceivedNotification(notification:)), name: Notification.Name("pushProductViewNew"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.openSearchView(notification:)), name: Notification.Name("openSearchView"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.NewDataLoadNotification(notification:)), name: Notification.Name("RemoveGestureNewPhoto"), object: nil)
        if AppUtilities.sharedInstance.GetBoolForObserver(str: "NewPhoto") != "1"{
        }
        if AppUtilities.sharedInstance.isactivemode{
            // here open view image
            let imageInfo = JTSImageInfo()
            imageInfo.imageURL = URL(string: (AppUtilities.sharedInstance.ImagePrivewDict.object(forKey: "url") as? String)!)
            imageInfo.istrading = AppUtilities.sharedInstance.ImagePrivewDict.object(forKey: "Istrading") as! String
            imageInfo.title = AppUtilities.sharedInstance.ImagePrivewDict.object(forKey: "title") as? String
            imageInfo.altText = AppUtilities.sharedInstance.ImagePrivewDict.object(forKey: "altText") as? String
            imageInfo.thumbnail =  AppUtilities.sharedInstance.ImagePrivewDict.object(forKey: "Thumbnail") as? String
            let imageViewer = JTSImageViewController(imageInfo: imageInfo, arry: nil, index: 0, mode: .image, backgroundStyle: .blurred)
            print(imageInfo)
            imageViewer?.show(from: self, transition: .center)
            AppUtilities.sharedInstance.isactivemode = false
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
         setGestureInCollectionview()
        AppUtilities.lockOrientation(.all)
        UIApplication.shared.statusBarStyle = .default
        if Isopen == false{
            self.perform(#selector(self.startTimer), with: nil, afterDelay: 5.0)
        }
        if AppUtilities.sharedInstance.appDelegate.is_Landscape != UIDevice.current.orientation.isLandscape{
            self.ImageCollectionview.reloadData()
        }
        Isopen = true
    }
    override func viewWillDisappear(_ animated: Bool) {
        stopTimer()
        NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(startTimer), object: nil)
        Isopen = false
        //NotificationCenter.default.removeObserver(self, name: Notification.Name("RemoveGestureNewPhoto"), object: nil)
    }
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        if Isopen == false{
            //  stopSamllTimer()
            self.ImageCollectionview .stopScrolling()
            self.ImageCollectionview.reloadData()
            return
        }else{
            // stopSamllTimer()
            if UIDevice.current.orientation.isLandscape {
                AppUtilities.sharedInstance.appDelegate.is_Landscape = true
                print("Landscape")
                self.ImageCollectionview.reloadData()
            } else {
                AppUtilities.sharedInstance.appDelegate.is_Landscape = false
                print("Portrait")
                self.ImageCollectionview.reloadData()
            }
            self.ImageCollectionview .stopScrolling()
        }
    }
    func NewDataLoadNotification(notification: Notification){
        if notification.userInfo != nil{
            self.setGestureInCollectionview()
        }else{
            ImageCollectionview.removeGestureRecognizer(swipeRight!)
            ImageCollectionview.removeGestureRecognizer(swipeleft!)
        }
    }
    func openSearchView(notification: Notification){
        self.stopTimer()
        let dict : NSDictionary = notification.userInfo! as NSDictionary
        print(dict)
        if Isswipe == true{
            self.dismissPopupViewControllerWithanimationType(MJPopupViewAnimationSlideLeftRight)
        }
        let view: ProductShippingViewController = (self.storyboard?.instantiateViewController(withIdentifier: "ProductShippingViewController"))! as! ProductShippingViewController
        view.newphotoasset = String(format: "%@", dict.value(forKey: "Url") as! NSString) as NSString
        view.ThumbnailURL = String(format: "%@", dict.value(forKey: "Thumbnail") as! NSURL) as NSString
        AppUtilities.lockOrientation(.portrait)
        self.navigationController?.pushViewController(view, animated: true)
//            let viewController: SearchViewController = (self.storyboard?.instantiateViewController(withIdentifier: "SearchViewController"))! as! SearchViewController
//            
//            let aObjNavi = UINavigationController(rootViewController: viewController)
//            aObjNavi.isNavigationBarHidden = true
//            present(aObjNavi, animated: false, completion: nil)
//            let viewController: TradingViewController = (self.storyboard?.instantiateViewController(withIdentifier: "TradingViewController"))! as! TradingViewController
//            
//            let aObjNavi = UINavigationController(rootViewController: viewController)
//            aObjNavi.isNavigationBarHidden = true
//            present(aObjNavi, animated: false, completion: nil)
    }
    //MARK:- Gesture Methods
    func setGestureInCollectionview(){
         swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.SwipeGesture))
        swipeRight?.direction = UISwipeGestureRecognizerDirection.right
        ImageCollectionview.addGestureRecognizer(swipeRight!)
         swipeleft = UISwipeGestureRecognizer(target: self, action: #selector(self.SwipeGesture))
        swipeleft?.direction = UISwipeGestureRecognizerDirection.left
        ImageCollectionview.addGestureRecognizer(swipeleft!)
    }
    func SwipeGesture(_ gesture: UIGestureRecognizer) {
        self.ImageCollectionview.stopScrolling()
        self.stopTimer()
      // self.dismiss(animated: false, completion: nil)
        if let swipeGesture = gesture as? UISwipeGestureRecognizer {
            switch swipeGesture.direction {
            case UISwipeGestureRecognizerDirection.right:
                print("Swiped right")
                Isswipe = true
                let viewController: TradingViewController = (self.storyboard?.instantiateViewController(withIdentifier: "TradingViewController"))! as! TradingViewController
                let aObjNavi = UINavigationController(rootViewController: viewController)
                aObjNavi.isNavigationBarHidden = true
                present(aObjNavi, animated: false, completion: {
                  //  AppUtilities.sharedInstance.GiveShadowToMainView(View: viewController.MainView!, offset: CGSize(width: 5.0, height: 5.0))
                     viewController.MainView.frame = CGRect(x: -viewController.view!.frame.size.width, y: 0, width: viewController.view!.frame.size.width, height: viewController.MainView.frame.size.height)
                    UIView.animate(withDuration: ViewChangeAnimationDuration, delay: 0.0, options: [.curveEaseOut], animations: {
                          viewController.view!.frame.origin = CGPoint(x: 0, y: 0)
                        self.view.layoutIfNeeded()
                    }, completion: { (finished: Bool) in
                        //AppUtilities.sharedInstance.RemoveShadows(View: viewController.MainView!)
                    })
                })
               // self.presentPopupViewController(aObjNavi, animationType: MJPopupViewAnimationSlideLeftRight)
            case UISwipeGestureRecognizerDirection.left:
                print("Swiped left")
                 //Searching
                Isswipe = true
                let viewController: SearchViewController = (self.storyboard?.instantiateViewController(withIdentifier: "SearchViewController"))! as! SearchViewController
                let aObjNavi = UINavigationController(rootViewController: viewController)
                aObjNavi.isNavigationBarHidden = true
                present(aObjNavi, animated: false, completion: {
                  // AppUtilities.sharedInstance.GiveShadowToMainView(View: viewController.view!, offset: CGSize(width: -5.0, height: 5.0))
                     viewController.view!.frame = CGRect(x: viewController.view!.frame.size.width, y: 0, width: viewController.view!.frame.size.width, height: viewController.view!.frame.size.height)
                    UIView.animate(withDuration: ViewChangeAnimationDuration, delay: 0.0, options: [.curveEaseIn], animations: {
                        viewController.view!.frame.origin = CGPoint(x: 0, y: 0)
                        self.view.layoutIfNeeded()
                    }, completion: { (finished: Bool) in
                       // AppUtilities.sharedInstance.RemoveShadows(View: viewController.view!)
                    })
                })
               //self.presentPopupViewController(aObjNavi, animationType: MJPopupViewAnimationSlideRightLeft)
            default:
                break
            }
        }
    }
    func methodOfReceivedNotification(notification: Notification){
        //Take Action on Notification
        print(notification.userInfo!)
        if Isswipe == true{
            self.dismissPopupViewControllerWithanimationType(MJPopupViewAnimationSlideLeftRight)
        }
        let dict : NSDictionary = notification.userInfo! as NSDictionary
       // let navi : UINavigationController = UINavigationController()
        let view: ProductShippingViewController = (self.storyboard?.instantiateViewController(withIdentifier: "ProductShippingViewController"))! as! ProductShippingViewController
        view.newphotoasset = String(format: "%@", dict.value(forKey: "Url") as! NSString) as NSString
        view.ThumbnailURL = String(format: "%@", dict.value(forKey: "Thumbnail") as! NSURL) as NSString
        AppUtilities.lockOrientation(.portrait)
        self.navigationController?.pushViewController(view, animated: true)
        //navi.pushViewController(view, animated: true)
    }
    //MARK:- Scrolling Methods
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        self.ImageCollectionview .stopScrolling()
        if !decelerate {
            print(decelerate)
            stopTimer()
            self.perform(#selector(self.startTimer), with: nil, afterDelay: 5.0)
        }else{
            stopTimer()
        }
    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.ImageCollectionview .stopScrolling()
        isscrolling = false
        if isscrolling == false{
            self.perform(#selector(self.startTimer), with: nil, afterDelay: 5.0)
        }
    }
    //MARK:- Timer Init and Close
    func startTimer() {
        if Globaltimer == nil {
            Globaltimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(self.loop), userInfo: nil, repeats: false)
            print("timer start")
        }
    }
    func stopTimer() {
        if Globaltimer != nil {
            Globaltimer?.invalidate()
            Globaltimer = nil
            print("timer Stop")
        }
    }
    func loop() {
        self.ImageCollectionview .startScrolling()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //MARK:- Collectionview method
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        if (self.arr_responseObject.count > 0 ){
            return self.arr_responseObject.count
        }else{
            return 0
        }
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        // get a reference to our storyboard cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell",for: indexPath as IndexPath)
        let dict : NSDictionary = self.arr_responseObject[indexPath.row] as! NSDictionary
        let img_view = cell.viewWithTag(20) as! UIImageView
        img_view.contentMode = .scaleAspectFit
        img_view.downloadImageFrom((dict["urls"] as! NSDictionary)["small"] as! String, contentMode: .scaleAspectFit)
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {
        let dict : NSDictionary = self.arr_responseObject[indexPath.row] as! NSDictionary
        let arrSend : NSMutableArray = NSMutableArray()
        for index in 0..<self.arr_responseObject.count{
            let dictTemp : NSDictionary = self.arr_responseObject[index] as! NSDictionary
            let imageInfo = JTSImageInfo()
            imageInfo.istrading = "0"
            imageInfo.imageURL = URL(string: ((dictTemp.value(forKeyPath: "urls") as! NSDictionary).value(forKeyPath: "regular") as! NSString) as String)
            imageInfo.title = ((dictTemp.value(forKeyPath: "user") as! NSDictionary).value(forKey: "name") as! NSString) as String!
            imageInfo.thumbnail = ((dictTemp.value(forKeyPath: "urls") as! NSDictionary).value(forKeyPath: "thumb") as! NSString) as String!
            imageInfo.altText = ((dictTemp.value(forKeyPath: "user") as! NSDictionary).value(forKey: "links") as! NSDictionary).value(forKeyPath: "html") as! String!
            arrSend.add(imageInfo)
        }
        let imageInfo = JTSImageInfo()
        AppUtilities.sharedInstance.SetBoolForObserver(str: "NewPhoto", value: "1")
        let previewurl = ((dict.value(forKeyPath: "urls") as! NSDictionary).value(forKeyPath: "full") as! NSString) as String
        print(previewurl)
        let newpreview = previewurl.replacingOccurrences(of: "q=85", with: "q=60&w=1000&h=1000")
        print(newpreview)
        imageInfo.imageURL = URL(string: newpreview)
        imageInfo.title = ((dict.value(forKeyPath: "user") as! NSDictionary).value(forKey: "name") as! NSString) as String!
        imageInfo.thumbnail = ((dict.value(forKeyPath: "urls") as! NSDictionary).value(forKeyPath: "full") as! NSString) as String!
        imageInfo.altText = ((dict.value(forKeyPath: "user") as! NSDictionary).value(forKey: "links") as! NSDictionary).value(forKeyPath: "html") as! String!
        imageInfo.istrading = "0"
        let photoid = indexPath.row
        let imageViewer = JTSImageViewController(imageInfo: imageInfo, arry: arrSend, index: photoid, mode: .image, backgroundStyle: .blurred)
        imageViewer?.show(from: self, transition: .center)
        //NotificationCenter.default.post(name: NSNotification.Name("RemoveGestureNewPhoto"), object: nil, userInfo: nil)
    }
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        lastcellindex = indexPath.row
        if Globaltimer != nil{
            self.ImageCollectionview .startScrolling()
        }
        if self.lastcellindex == self.arr_responseObject.count - 1{
            self.ImageCollectionview.triggerInfiniteScrolling()
        }
    }
    func collectionView(collectionView: UICollectionView,
                        heightForImageAtIndexPath indexPath: IndexPath,
                        withWidth: CGFloat) -> CGFloat {
        let dict : NSDictionary = self.arr_responseObject[indexPath.row] as! NSDictionary
        let actualWidth = dict["width"] as? Int ?? 1
        let actualHeight = dict["height"] as? Int ?? 1
        let actualRatio : Float = Float(actualWidth) / Float(actualHeight)
        let framesize : Float = Float(collectionView.frame.size.width - 10) / Float(3)
        return CGFloat(framesize / actualRatio)
    }
    func collectionView(collectionView: UICollectionView,
                        heightForAnnotationAtIndexPath indexPath: IndexPath,
                        withWidth: CGFloat) -> CGFloat {
        return 0
    }
    //MARK:- WebService Call
    func callWebserviceAuthorize(pageindex : Int , Pagesize : Int){
        if AppUtilities.sharedInstance.isNetworkRechable(){
            IsFinish = true
             let url = "https://api.unsplash.com/photos/?page=\(pageindex)&per_page=\(Pagesize)&order_by=new&client_id=\(APP_ID)"
            print(url)
            manager.responseSerializer = AFHTTPResponseSerializer()
            manager.get(
                url,
                parameters: nil,
                success:
                {
                    (operation, responseObject) in
                    let json = try? JSONSerialization.jsonObject(with: responseObject as! Data, options: [])
                    if let arr : NSArray = json as? NSArray
                    {
                        if self.pageCount == 1
                        {
                            self.LightHeaderView.alpha = 1.0
                            UIView.animate(withDuration: 5.0, animations: {
                                self.LightHeaderView.alpha = 0.0
                                self.view.layoutIfNeeded()
                            })
                            self.ImageCollectionview.stopScrolling()
                            self.arr_responseObject.removeAllObjects()
                        }else{
                        }
                        self.arr_responseObject.addObjects(from: NSMutableArray(array: arr) as! [Any])
                       print(self.arr_responseObject.value(forKeyPath: "urls") as? NSArray)
                        self.IsFinish = false
                        self.ImageCollectionview.infiniteScrollingView.stopAnimating()
                        self.ImageCollectionview.reloadData()
                        if self.pageCount == 1
                        {
                            if self.isAppfirst != false{
                                self.perform(#selector(self.startTimer), with: nil, afterDelay: 0.3)
                            }
                        }
                    }
                    GIFProgressHUD .hide(for: self.view, animated: true)
            },
                failure:
                {
                    (operation, error) in
                    print("Error: " + (error?.localizedDescription)!)
                    self.IsFinish = false
                    AppUtilities.sharedInstance.showAlert(title: "Error", msg: (error?.localizedDescription)! as NSString)
                    self.callWebserviceAuthorize(pageindex: self.pageCount, Pagesize:  self.pageSize)
                    self.stopTimer()
            })
        }else{
            AppUtilities.sharedInstance.showAlert(title: "No Internet", msg: "No Internet Connection . please check your Internet.")
        }
    }
}