//
//  ItemImagePickerViewController.swift
//  Vendoo
//
//  Created by Okechi Onyeje on 5/27/16.
//  Copyright © 2016 Okechi Onyeje. All rights reserved.
//

/*
 need to make this class display a top navigation bar so user may cancel the new item posting if need be
 */

import UIKit


class ItemImagePickerViewController: UIViewController {
    
    //Outlets
    @IBOutlet weak var cancelButton: UIButton!
    
    @IBOutlet weak var possibleItemImageMain: UIImageView!
    @IBOutlet weak var possibleItemImage2: UIImageView!
    @IBOutlet weak var possibleItemImage3: UIImageView!
    @IBOutlet weak var possibleItemImage4: UIImageView!
    @IBOutlet weak var possibleItemImage5: UIImageView!
    @IBOutlet weak var itemQuantity: UITextField!
    @IBOutlet weak var itemName: UITextField!
    @IBOutlet weak var itemDescription: UITextView!
    @IBOutlet weak var itemPrice: UITextField!
    @IBOutlet weak var categoryPicker: UIPickerView!
    @IBOutlet weak var containerScrollView: UIScrollView!
    
    //class variables
    var pickerData: [String] = [String]()
    var itemImagesSelections = [false,false,false,false,false]
    private var picker = UIImagePickerController()
    private var currImageSelected: UIImageView!
    private var currUILabel: UILabel!
    private var imageIndex: Int!
    private var isEditing: Bool = false
    private var currentInformation: Dictionary<String, AnyObject>!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        self.tabBarController?.tabBar.hidden = true
        
        // Connect data:
        self.categoryPicker.delegate = self
        self.categoryPicker.dataSource = self
        self.itemDescription.delegate = self
        self.itemName.delegate = self
        self.itemQuantity.delegate = self
        self.itemPrice.delegate = self
        self.picker.delegate = self
        
        let tapGestureMain = UITapGestureRecognizer(target: self, action: #selector(ItemImagePickerViewController.takePicture))
        self.view.addGestureRecognizer(tapGestureMain)

        if(self.isEditing) {
            self.itemName.text = self.currentInformation["title"] as? String
            self.itemDescription.text = self.currentInformation["description"] as? String
            self.itemQuantity.text = self.currentInformation["quantity"] as? String
            self.itemPrice.text = self.currentInformation["price"] as? String

            //@FIXME: Cancel button not changing to Back button label
            dispatch_async(dispatch_get_main_queue(), {
                self.cancelButton.titleLabel?.text = "Back"
            })
            
            var images = (self.currentInformation["images"] as? [UIImage])!
            for i in 0...(images.count - 1) {
                switch i {
                case 0:
                    self.possibleItemImageMain.image = images[i]
                    self.itemImagesSelections[i] = true
                    break
                case 1:
                    self.possibleItemImage2.image = images[i]
                    self.itemImagesSelections[i] = true
                    break
                case 2:
                    self.possibleItemImage3.image = images[i]
                    self.itemImagesSelections[i] = true
                    break
                case 3:
                    self.possibleItemImage4.image = images[i]
                    self.itemImagesSelections[i] = true
                    break
                case 4:
                    self.possibleItemImage5.image = images[i]
                    self.itemImagesSelections[i] = true
                    break
                default:
                    break
                }
            }
            
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.hidden = true
    }
    
    func toggleEditingMode(dictionary: Dictionary<String, AnyObject>?){
        if(!self.isEditing) {
            self.currentInformation = dictionary!
        }
        self.isEditing = !self.isEditing
    }
    
}

//MARK: - Navigation methods
extension ItemImagePickerViewController {
    
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
        
        if(segue.identifier == "CategoriesSegue"){
            print(self.itemName.text!)
            print(self.itemDescription.text!)
            print(self.possibleItemImageMain.image)
            print(self.itemPrice.text!)
            
            var dict: Dictionary<String, AnyObject!> = ["title":self.itemName.text!, "description":self.itemDescription.text!, "price":self.itemPrice.text!, "quantity":self.itemQuantity.text!]
            var counter = 0
            var images: [UIImageView] = []
            for bool in self.itemImagesSelections {
                if !bool {
                    break
                }
                switch counter {
                case 1:
                    images.append(self.possibleItemImage2)
                    break
                case 2:
                    images.append(self.possibleItemImage3)
                    break
                case 3:
                    images.append(self.possibleItemImage4)
                    break
                case 4:
                    images.append(self.possibleItemImage5)
                    break
                default:
                    images.append(self.possibleItemImageMain)
                }
                counter += 1
            }
            
            dict["pictures"] = images
            (segue.destinationViewController as! CategoriesTableViewController).setListingDictionary(dict)
            
            if(self.isEditing) {
                    (segue.destinationViewController as! CategoriesTableViewController).setManagers((self.currentInformation["fbManager"] as? FacebookGraphAPIManager)!, fireManager: (self.currentInformation["firebaseManager"] as? FirebaseManager)!, ebayManager: (self.currentInformation["ebayManager"] as? EbayWebServiceManager)!, etsyManager: (self.currentInformation["etsyManager"] as? EtsyRESTAPIManager)!)
                
            }else {
                (segue.destinationViewController as! CategoriesTableViewController).setManagers(((self.tabBarController as? HomeViewController)?.fbGraphManager)!,
                                                                                                fireManager: ((self.tabBarController as? HomeViewController)?.firebaseManager)!, ebayManager: ((self.tabBarController as? HomeViewController)?.ebayGraphManager)!,
                                                                                                etsyManager: ((self.tabBarController as? HomeViewController)?.etsyManager)!)
            }
        }
        
        
    }
    
}

//MARK: - Camera session methods
extension ItemImagePickerViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        if (self.possibleItemImageMain.image != nil && self.currUILabel != nil ){
            self.currUILabel.hidden = true
        }
        self.currImageSelected.image = image
        self.itemImagesSelections[self.imageIndex] = true
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    func takePicture(sender: UITapGestureRecognizer ){
        let location: CGPoint = sender.locationInView(self.view)
        
        if(sender.state == UIGestureRecognizerState.Ended) {
            var viewsWereSaved = [false, false]
            for view in self.view.subviews {
                if (view.isKindOfClass(UIImageView) && CGRectContainsPoint(view.frame, location)) {
                    self.currImageSelected = view as! UIImageView
                    switch (view.tag) {
                    case 1:
                        if(self.itemImagesSelections[0]) {
                            //self.itemImagesSelections[1] = true
                            viewsWereSaved[0] = true
                            
                            self.imageIndex = 1
                            accessCam()
                        } else {
                            let alert = UIAlertController(title: "Main Image Needed", message: "You must have a main image before saving supporting images.", preferredStyle: .Alert)
                            alert.addAction(UIAlertAction(title: "OK", style: .Default, handler:{(action: UIAlertAction!) in alert.dismissViewControllerAnimated(true, completion: nil)}))
                            
                            self.presentViewController(alert, animated: true, completion: nil)
                            
                        }
                        break
                        
                    case 2:
                        if(self.itemImagesSelections[0] && self.itemImagesSelections[1]) {
                            viewsWereSaved[0] = true
                            
                            self.imageIndex = 2
                            accessCam()
                        } else {
                            let alert = UIAlertController(title: "Support Image 1 Missing", message: "You must save your first supporting image before saving more.", preferredStyle: .Alert)
                            alert.addAction(UIAlertAction(title: "OK", style: .Default, handler:{(action: UIAlertAction!) in alert.dismissViewControllerAnimated(true, completion: nil)}))
                            
                            self.presentViewController(alert, animated: true, completion: nil)
                            
                        }
                        break
                    case 3:
                        if(self.itemImagesSelections[0] && self.itemImagesSelections[1]
                            && self.itemImagesSelections[2]) {
                            viewsWereSaved[0] = true
                            
                            self.imageIndex = 3
                            accessCam()
                        } else {
                            let alert = UIAlertController(title: "Support Image 2 Missing", message: "You must save your first two supporting images before saving more.", preferredStyle: .Alert)
                            alert.addAction(UIAlertAction(title: "OK", style: .Default, handler:{(action: UIAlertAction!) in alert.dismissViewControllerAnimated(true, completion: nil)}))
                            
                            self.presentViewController(alert, animated: true, completion: nil)
                            
                        }
                        break
                    case 4:
                        if(self.itemImagesSelections[0] && self.itemImagesSelections[1]
                            && self.itemImagesSelections[2] && self.itemImagesSelections[3]) {
                            viewsWereSaved[0] = true
                            
                            self.imageIndex = 4
                            accessCam()
                        } else {
                            let alert = UIAlertController(title: "Support Image 3 Missing", message: "You must save your first three supporting images before saving more.", preferredStyle: .Alert)
                            alert.addAction(UIAlertAction(title: "OK", style: .Default, handler:{(action: UIAlertAction!) in alert.dismissViewControllerAnimated(true, completion: nil)}))
                            
                            self.presentViewController(alert, animated: true, completion: nil)
                            
                        }
                        break
                    default:
                        //self.itemImagesSelections[0] = true
                        
                        self.imageIndex = 0
                        accessCam()
                        break
                    }
                    
                }
                if (view.isKindOfClass(UILabel) && CGRectContainsPoint(view.frame, location)) {
                    self.currUILabel = view as! UILabel
                    viewsWereSaved[1] = true
                }
            }
        }
        
        
    }
    
    private func accessCam(){
        let captureMenu = UIAlertController(title: nil, message:nil, preferredStyle: .ActionSheet)
        
        let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {
            (alert: UIAlertAction!) -> Void in
        })
        
        let cameraAction = UIAlertAction(title: "Take a New Pic", style: .Default, handler: {
            (alert: UIAlertAction!) -> Void in
            self.picker.allowsEditing = false
            self.picker.sourceType = UIImagePickerControllerSourceType.Camera
            self.picker.cameraCaptureMode = .Photo
            self.presentViewController(self.picker, animated: true, completion: nil)
            
        })
        
        let galleryAction = UIAlertAction(title: "Select a Profile Pic", style: .Default, handler: {
            (alert: UIAlertAction!) -> Void in
            self.picker.allowsEditing = false
            self.picker.sourceType = .PhotoLibrary
            self.presentViewController(self.picker, animated: true, completion: nil)
        })
        
        captureMenu.addAction(galleryAction)
        captureMenu.addAction(cameraAction)
        captureMenu.addAction(cancelAction)
        self.presentViewController(captureMenu, animated: true, completion: nil)
    }
    
}




//MARK: - UIPickerViewDelegate
extension ItemImagePickerViewController: UIPickerViewDelegate {
    
    // Catpure the picker view selection
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        // This method is triggered whenever the user makes a change to the picker selection.
        // The parameter named row and component represents what was selected.
    }
    
}

//MARK: - UIPickerViewDatasource
extension ItemImagePickerViewController: UIPickerViewDataSource {
    
    // The number of columns of data
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
    
    // The number of rows of data
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData.count
    }
    
    // The data to return for the row and component (column) that's being passed in
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return pickerData[row]
    }
    
    
    
}

extension ItemImagePickerViewController: UITextViewDelegate {
    
    func textViewDidBeginEditing(textView: UITextView) {
        if (textView.text! == "Description") {
            textView.text = ""
            textView.textColor = UIColor.blackColor()
            //optional
        }
        self.containerScrollView.setContentOffset(CGPointMake(0, 200), animated: true)
        textView.becomeFirstResponder()
    }
    
    func textViewDidEndEditing(textView: UITextView) {
        if (textView.text! == "") {
            textView.text = "Description"
            textView.textColor = UIColor.lightGrayColor()
            //optional
        }
        textView.resignFirstResponder()
    }
    
    func textViewDidChange(textView: UITextView) {
        let fixedWidth = textView.frame.size.width
        textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
        let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
        var newFrame = textView.frame
        newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
        textView.frame = newFrame;
        self.containerScrollView.setContentOffset(CGPointMake(0, 0), animated: true)
    }
    
    
}

extension ItemImagePickerViewController: UITextFieldDelegate {
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return false
    }
    
    func hideKeyboard() {
        self.view.endEditing(true)
    }
    
    func textFieldDidBeginEditing(textField: UITextField) {
        self.containerScrollView.setContentOffset(CGPointMake(0, 200), animated: true)
    }
    
    func textFieldDidEndEditing(textField: UITextField) {
        self.containerScrollView.setContentOffset(CGPointMake(0, 0), animated: true)
    }
}

//Mark: - IBActions
extension ItemImagePickerViewController {
    
    @IBAction func chooseSellerNetworks(sender: AnyObject) {
        
        //segue to networks selection
        self.performSegueWithIdentifier("SelectNetworkSegue", sender: self)
    }
    
    @IBAction func draftItem(sender: AnyObject) {
        
        if(self.possibleItemImageMain.image == nil){
            let alert = UIAlertController(title: "Main Image Needed", message: "To proceed to save your listing as a draft, you must supply at least one picture for your listing.", preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "OK", style: .Default, handler:{(action: UIAlertAction!) in alert.dismissViewControllerAnimated(true, completion: nil)}))
            
            self.presentViewController(alert, animated: true, completion: nil)
        }else{
            
            //save listing to private user path in firebase
            let newListingRef = (self.tabBarController as? HomeViewController)?.firebaseManager.ref.child("Users").child("\(((self.tabBarController as? HomeViewController)?.firebaseManager.user_email)!)").child("user_Listings").childByAutoId()
            
            let category = (self.pickerData[self.categoryPicker.selectedRowInComponent(0)])
            var counter = -1
            for bool in self.itemImagesSelections {
                if bool {
                    counter += 1
                }else {
                    break
                }
            }
            let listing: Dictionary<String, AnyObject?> = ["listingID": newListingRef!.key,
                                                           "seller email": (NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)!,
                                                           "listingTitle": self.itemName.text,
                                                           "listingPrice": self.itemPrice.text,
                                                           "listingCategory": category,
                                                           "listingDescription": self.itemDescription.text,
                                                           "numberOfSupportingImages" : counter,
                                                           "isListingDraft": true,
                                                           "networks": ["areNetworksChosen": false]]
            
            (self.tabBarController as? HomeViewController)?.firebaseManager.ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
                
                let databaseDict = snapshot.value as! [String : AnyObject]
                
                let storageRef = (self.tabBarController as? HomeViewController)?.firebaseManager.storage.referenceForURL((databaseDict["image_storage"] as? String)!)
                
                //check each imageview to see if there is an image to upload
                if(self.possibleItemImage2.image != nil){
                    let listingImageRef = storageRef!.child("images/\(newListingRef!.key)"+"/2.jpg")
                    
                    listingImageRef.putData(UIImageJPEGRepresentation(self.possibleItemImage2.image!, 0.8)!, metadata: nil,completion:
                        {(metadata, error) -> Void in
                            print(metadata)
                    })
                }
                
                if(self.possibleItemImage3.image != nil){
                    let listingImageRef = storageRef!.child("images/\(newListingRef!.key)"+"/3.jpg")
                    
                    listingImageRef.putData(UIImageJPEGRepresentation(self.possibleItemImage3.image!, 0.8)!, metadata: nil,completion:
                        {(metadata, error) -> Void in
                            print(metadata)
                    })
                }
                
                if(self.possibleItemImage4.image != nil){
                    let listingImageRef = storageRef!.child("images/\(newListingRef!.key)"+"/4.jpg")
                    
                    listingImageRef.putData(UIImageJPEGRepresentation(self.possibleItemImage4.image!, 0.8)!, metadata: nil,completion:
                        {(metadata, error) -> Void in
                            
                    })
                }
                
                if(self.possibleItemImage5.image != nil){
                    let listingImageRef = storageRef!.child("images/\(newListingRef!.key)"+"/5.jpg")
                    
                    listingImageRef.putData(UIImageJPEGRepresentation(self.possibleItemImage5.image!, 0.8)!, metadata: nil,completion:
                        {(metadata, error) -> Void in
                            
                    })
                }
                
                if(self.possibleItemImageMain.image != nil){
                    let listingImageRef = storageRef!.child("images/\(newListingRef!.key)"+"/main.jpg")
                    
                    listingImageRef.putData(UIImageJPEGRepresentation(self.possibleItemImageMain.image!, 0.8)!, metadata: nil,completion:
                        {(metadata, error) -> Void in
                            
                            newListingRef!.setValue(listing as? Dictionary<String,AnyObject>)
                            let alert = UIAlertController(title: "Item Saved", message: "Your listing has been saved by a draft", preferredStyle: .Alert)
                            
                            alert.addAction(UIAlertAction(title: "OK", style: .Default, handler:{(action: UIAlertAction!) in alert.dismissViewControllerAnimated(true, completion: {
                                
                                self.dismissViewControllerAnimated(true, completion: nil)
                            })}))
                            
                            self.presentViewController(alert, animated: true, completion: nil)
                    })
                }
            })
            
        }
        
        
    }
    
    @IBAction func cancelNewListing(sender: AnyObject) {
        //@FIXME: nil out all data user may have entered so that when they reopen new listing page it initialized to a fresh screen.
        
        if(!self.isEditing) {
            self.tabBarController?.selectedIndex = 0
        }else{
            self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
        }
    }
    
    
}
