<commit_before>//
//  SocialWorkInstagramViewController.swift
//  Yep
//
//  Created by NIX on 15/5/14.
//  Copyright (c) 2015年 Catch Inc. All rights reserved.
//

import UIKit

class SocialWorkInstagramViewController: BaseViewController {

    var socialAccount: SocialAccount?
    var profileUser: ProfileUser?
    var instagramWork: InstagramWork?

    var afterGetInstagramWork: (InstagramWork -> Void)?


    lazy var shareButton: UIBarButtonItem = {
        let button = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: "share")
        return button
        }()

    @IBOutlet weak var instagramCollectionView: UICollectionView!

    let instagramMediaCellIdentifier = "InstagramMediaCell"

    lazy var collectionViewWidth: CGFloat = {
        return CGRectGetWidth(self.instagramCollectionView.bounds)
        }()

    var instagramMedias = Array<InstagramWork.Media>() {
        didSet {
            updateInstagramCollectionView()

            if let firstMedia = instagramMedias.first {
                shareButton.enabled = true
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        animatedOnNavigationBar = false

        if let socialAccount = socialAccount {
            let accountImageView = UIImageView(image: UIImage(named: socialAccount.iconName)!)
            accountImageView.tintColor = socialAccount.tintColor
            navigationItem.titleView = accountImageView

        } else {
            title = "Instagram"
        }

        shareButton.enabled = false
        navigationItem.rightBarButtonItem = shareButton

        instagramCollectionView.registerNib(UINib(nibName: instagramMediaCellIdentifier, bundle: nil), forCellWithReuseIdentifier: instagramMediaCellIdentifier)

        if let gestures = navigationController?.view.gestureRecognizers {
            for recognizer in gestures {
                if recognizer.isKindOfClass(UIScreenEdgePanGestureRecognizer) {
                    instagramCollectionView.panGestureRecognizer.requireGestureRecognizerToFail(recognizer as! UIScreenEdgePanGestureRecognizer)
                    println("Require UIScreenEdgePanGestureRecognizer to failed")
                    break
                }
            }
        }

        // 获取 Instagram Work，如果必要的话

        if let instagramWork = instagramWork {
            self.instagramMedias = instagramWork.medias
            
        } else {
            var userID: String?

            if let profileUser = profileUser {
                switch profileUser {
                case .DiscoveredUserType(let discoveredUser):
                    userID = discoveredUser.id
                case .UserType(let user):
                    userID = user.userID
                }
            }

            if let userID = userID {

                instagramWorkOfUserWithUserID(userID, failureHandler: { [weak self] (reason, errorMessage) -> Void in
                    defaultFailureHandler(reason, errorMessage)

                    YepAlert.alertSorry(message: NSLocalizedString("Network is not good!", comment: ""), inViewController: self)

                }, completion: { instagramWork in
                    println("instagramWork: \(instagramWork.medias.count)")

                    dispatch_async(dispatch_get_main_queue()) {
                        self.instagramMedias = instagramWork.medias

                        self.afterGetInstagramWork?(instagramWork)
                    }
                })
            }
        }
    }

    // MARK: Actions

    func updateInstagramCollectionView() {
        dispatch_async(dispatch_get_main_queue()) {
            self.instagramCollectionView.reloadData()
        }
    }

    func share() {

        if let firstMedia = instagramMedias.first {

            let profileURLString = "https://instagram.com/" + firstMedia.username

            if let profileURL = NSURL(string: profileURLString) {

                let activityViewController = UIActivityViewController(activityItems: [profileURL], applicationActivities: nil)

                presentViewController(activityViewController, animated: true, completion: nil)
            }
        }
    }

}

extension SocialWorkInstagramViewController: UICollectionViewDataSource, UICollectionViewDelegate {

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return instagramMedias.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(instagramMediaCellIdentifier, forIndexPath: indexPath) as! InstagramMediaCell
<commit_msg>share Instagram with WeChat<commit_after>//
//  SocialWorkInstagramViewController.swift
//  Yep
//
//  Created by NIX on 15/5/14.
//  Copyright (c) 2015年 Catch Inc. All rights reserved.
//

import UIKit

class SocialWorkInstagramViewController: BaseViewController {

    var socialAccount: SocialAccount?
    var profileUser: ProfileUser?
    var instagramWork: InstagramWork?

    var afterGetInstagramWork: (InstagramWork -> Void)?


    lazy var shareButton: UIBarButtonItem = {
        let button = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: "share")
        return button
        }()

    @IBOutlet weak var instagramCollectionView: UICollectionView!

    let instagramMediaCellIdentifier = "InstagramMediaCell"

    lazy var collectionViewWidth: CGFloat = {
        return CGRectGetWidth(self.instagramCollectionView.bounds)
        }()

    var instagramMedias = Array<InstagramWork.Media>() {
        didSet {
            updateInstagramCollectionView()

            if let firstMedia = instagramMedias.first {
                shareButton.enabled = true
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        animatedOnNavigationBar = false

        if let socialAccount = socialAccount {
            let accountImageView = UIImageView(image: UIImage(named: socialAccount.iconName)!)
            accountImageView.tintColor = socialAccount.tintColor
            navigationItem.titleView = accountImageView

        } else {
            title = "Instagram"
        }

        shareButton.enabled = false
        navigationItem.rightBarButtonItem = shareButton

        instagramCollectionView.registerNib(UINib(nibName: instagramMediaCellIdentifier, bundle: nil), forCellWithReuseIdentifier: instagramMediaCellIdentifier)

        if let gestures = navigationController?.view.gestureRecognizers {
            for recognizer in gestures {
                if recognizer.isKindOfClass(UIScreenEdgePanGestureRecognizer) {
                    instagramCollectionView.panGestureRecognizer.requireGestureRecognizerToFail(recognizer as! UIScreenEdgePanGestureRecognizer)
                    println("Require UIScreenEdgePanGestureRecognizer to failed")
                    break
                }
            }
        }

        // 获取 Instagram Work，如果必要的话

        if let instagramWork = instagramWork {
            self.instagramMedias = instagramWork.medias
            
        } else {
            var userID: String?

            if let profileUser = profileUser {
                switch profileUser {
                case .DiscoveredUserType(let discoveredUser):
                    userID = discoveredUser.id
                case .UserType(let user):
                    userID = user.userID
                }
            }

            if let userID = userID {

                instagramWorkOfUserWithUserID(userID, failureHandler: { [weak self] (reason, errorMessage) -> Void in
                    defaultFailureHandler(reason, errorMessage)

                    YepAlert.alertSorry(message: NSLocalizedString("Network is not good!", comment: ""), inViewController: self)

                }, completion: { instagramWork in
                    println("instagramWork: \(instagramWork.medias.count)")

                    dispatch_async(dispatch_get_main_queue()) {
                        self.instagramMedias = instagramWork.medias

                        self.afterGetInstagramWork?(instagramWork)
                    }
                })
            }
        }
    }

    // MARK: Actions

    func updateInstagramCollectionView() {
        dispatch_async(dispatch_get_main_queue()) {
            self.instagramCollectionView.reloadData()
        }
    }

    func share() {

        if let firstMedia = instagramMedias.first {

            let profileURLString = "https://instagram.com/" + firstMedia.username

            if let profileURL = NSURL(string: profileURLString) {

                let title = String(format: NSLocalizedString("%@'s Instagram", comment: ""), firstMedia.username)

                var thumbnail: UIImage?
                if let socialAccount = socialAccount {
                    thumbnail = UIImage(named: socialAccount.iconName)
                }

                let message = WeChatActivity.Message(
                    title: title,
                    description: nil,
                    thumbnail: thumbnail,
                    media: .URL(profileURL)
                )

                let weChatSessionActivity = WeChatActivity(scene: .Session, message: message)
                let weChatTimelineActivity = WeChatActivity(scene: .Timeline, message: message)

                let activityViewController = UIActivityViewController(activityItems: [profileURL], applicationActivities: [weChatSessionActivity, weChatTimelineActivity])

                presentViewController(activityViewController, animated: true, completion: nil)
            }
        }
    }

}

extension SocialWorkInstagramViewController: UICollectionViewDataSource, UICollectionViewDelegate {

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return instagramMedias.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(instagramMediaCellIdentifier, forIndexPath: indexPath) as! InstagramMediaCell

{'fraction_non_alphanumeric': 0.06994473032208881, 'fraction_numerical': 0.001905850962454736, 'mean_word_length': 2.2583048742626515, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 15, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1374458', 'n_tokens_mistral': 2728, 'n_tokens_neox': 2548, 'n_words': 540}