<commit_before>//
//  NewsFeedServiceProvider.swift
//  Photostream
//
//  Created by <NAME> on 22/10/2016.
//  Copyright © 2016 <NAME>. All rights reserved.
//

import Foundation
import FirebaseDatabase

struct NewsFeedServiceProvider: NewsFeedService {
    
    var session: AuthSession
    
    init(session: AuthSession) {
        self.session = session
    }
    
    func fetchNewsFeed(offset: String, limit: UInt, callback: ((NewsFeedServiceResult) -> Void)?) {
        var result = NewsFeedServiceResult()
        guard session.isValid else {
            result.error = .authenticationNotFound(message: "Authentication not found")
            callback?(result)
            return
        }
        
        let uid = session.user.id
        let rootRef = FIRDatabase.database().reference()
        let feedRef = rootRef.child("user-feed").child(uid)
        let postsRef = feedRef.child("posts")
        var query = postsRef.queryOrderedByKey()
        
        if !offset.isEmpty {
            query = query.queryEnding(atValue: offset)
        }
        
        query = query.queryLimited(toLast: limit + 1)
        query.observeSingleEvent(of: .value, with: { (snapshot) in
            guard snapshot.childrenCount > 0 else {
                result.posts = PostList()
                callback?(result)
                return
            }
            
            var posts = [Post]()
            var users = [String: User]()
            
            for child in snapshot.children {
                guard let post = child as? FIRDataSnapshot else {
                    continue
                }
                
                let postKey = post.key
                let postRef = rootRef.child("posts").child(postKey)
                postRef.observeSingleEvent(of: .value, with: { (postSnapshot) in
                    guard let userId = postSnapshot.childSnapshot(forPath: "uid").value as? String,
                        let photoId = postSnapshot.childSnapshot(forPath: "photo_id").value as? String else {
                        return
                    }
                    
                    let userRef = rootRef.child("users").child(userId)
                    let photoRef = rootRef.child("photos").child(photoId)
                    let likesRef = rootRef.child("post-like/\(postKey)/likes")
                    
                    userRef.observeSingleEvent(of: .value, with: { (userSnapshot) in
                        photoRef.observeSingleEvent(of: .value, with: { (photoSnapshot) in
                            likesRef.observeSingleEvent(of: .value, with: { (likesSnapshot) in
                                if users[userId] == nil {
                                    users[userId] = User(with: userSnapshot, exception: "email")
                                }
                                
                                var post = Post(with: postSnapshot)
                                post.photo = Photo(with: photoSnapshot)
                                
                                if likesSnapshot.hasChild(uid) {
                                    post.isLiked = true
                                }
                                
                                if post.id == "-KYEBghKOtMEmX39ZEoK" {
                                    print("post '\(post.id)' -> isLiked ->", post.isLiked)
                                }
                                
                                posts.append(post)
                                
                                let postCount = UInt(posts.count)
                                if postCount == snapshot.childrenCount {
                                    if postCount == limit + 1 {
                                        let removedPost = posts.removeFirst()
                                        result.nextOffset = removedPost.id
                                    }

                                    var postList = PostList()
                                    postList.posts = posts.reversed()<commit_msg>Removed print.<commit_after>//
//  NewsFeedServiceProvider.swift
//  Photostream
//
//  Created by <NAME> on 22/10/2016.
//  Copyright © 2016 <NAME>. All rights reserved.
//

import Foundation
import FirebaseDatabase

struct NewsFeedServiceProvider: NewsFeedService {
    
    var session: AuthSession
    
    init(session: AuthSession) {
        self.session = session
    }
    
    func fetchNewsFeed(offset: String, limit: UInt, callback: ((NewsFeedServiceResult) -> Void)?) {
        var result = NewsFeedServiceResult()
        guard session.isValid else {
            result.error = .authenticationNotFound(message: "Authentication not found")
            callback?(result)
            return
        }
        
        let uid = session.user.id
        let rootRef = FIRDatabase.database().reference()
        let feedRef = rootRef.child("user-feed").child(uid)
        let postsRef = feedRef.child("posts")
        var query = postsRef.queryOrderedByKey()
        
        if !offset.isEmpty {
            query = query.queryEnding(atValue: offset)
        }
        
        query = query.queryLimited(toLast: limit + 1)
        query.observeSingleEvent(of: .value, with: { (snapshot) in
            guard snapshot.childrenCount > 0 else {
                result.posts = PostList()
                callback?(result)
                return
            }
            
            var posts = [Post]()
            var users = [String: User]()
            
            for child in snapshot.children {
                guard let post = child as? FIRDataSnapshot else {
                    continue
                }
                
                let postKey = post.key
                let postRef = rootRef.child("posts").child(postKey)
                postRef.observeSingleEvent(of: .value, with: { (postSnapshot) in
                    guard let userId = postSnapshot.childSnapshot(forPath: "uid").value as? String,
                        let photoId = postSnapshot.childSnapshot(forPath: "photo_id").value as? String else {
                        return
                    }
                    
                    let userRef = rootRef.child("users").child(userId)
                    let photoRef = rootRef.child("photos").child(photoId)
                    let likesRef = rootRef.child("post-like/\(postKey)/likes")
                    
                    userRef.observeSingleEvent(of: .value, with: { (userSnapshot) in
                        photoRef.observeSingleEvent(of: .value, with: { (photoSnapshot) in
                            likesRef.observeSingleEvent(of: .value, with: { (likesSnapshot) in
                                if users[userId] == nil {
                                    users[userId] = User(with: userSnapshot, exception: "email")
                                }
                                
                                var post = Post(with: postSnapshot)
                                post.photo = Photo(with: photoSnapshot)
                                
                                if likesSnapshot.hasChild(uid) {
                                    post.isLiked = true
                                }
                                
                                posts.append(post)
                                
                                let postCount = UInt(posts.count)
                                if postCount == snapshot.childrenCount {
                                    if postCount == limit + 1 {
                                        let removedPost = posts.removeFirst()
                                        result.nextOffset = removedPost.id
                                    }

                                    var postList = PostList()
                                    postList.posts = posts.reversed()
{'fraction_non_alphanumeric': 0.08274021352313167, 'fraction_numerical': 0.004067107269954245, 'mean_word_length': 1.1090860359153043, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 32, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '257907', 'n_tokens_mistral': 1863, 'n_tokens_neox': 1760, 'n_words': 399}