//
//  ViewController.swift
//  SLComposeFacebook
//
//  Created by Keith Welch on 9/13/15.
//  Copyright © 2015 Keith Welch. All rights reserved.
//

import UIKit
import Social
import MobileCoreServices

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    @IBOutlet weak var txtPost: UITextView!
    @IBOutlet weak var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func btnChoosePhotoTouched(sender: AnyObject) {
        if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum))
        {
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self;
            imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            imagePicker.allowsEditing = false
            presentViewController(imagePicker, animated: true, completion: nil)
        }
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        let mediaType = info[UIImagePickerControllerMediaType]
        dismissViewControllerAnimated(true, completion: nil)
        if ((mediaType?.isEqualToString(kUTTypeImage as String)) != nil) {
            let image:UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
            imageView.image = image;
        }
        
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @IBAction func viewTouched(sender: AnyObject) {
        txtPost.resignFirstResponder()
    }
    
    @IBAction func btnPostTouched(sender: AnyObject) {
        let controller = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
        if (imageView.image != nil) {
            controller.addImage(imageView.image)
        }
        controller.setInitialText(txtPost.text)
        presentViewController(controller, animated:true, completion:nil)
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

