<commit_before>//
//  PostsCollectionViewController.swift
//  a-simple-reddit-client
//
//  Created by <NAME> on 08/02/17.
//  Copyright © 2017 mourodrigo. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class PostsCollectionViewController: UICollectionViewController {

    var posts: Array<[AnyHashable : AnyObject]> = []
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewDidAppear(_ animated: Bool) {
        fetchPosts()
    }
    
    func fetchPosts(){
     
        let url = URL(string: "https://www.reddit.com/top/.json")!
        let session = URLSession.shared
        
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        
        request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
        
        let task = session.dataTask(with: request) { ( data, response, error) in
            
            do {
                
                let JSONReturn = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [AnyHashable : AnyObject]
                
                self.posts = JSONReturn["data"]?["children"] as! Array<[String : AnyObject]>
                self.collectionView?.reloadData()
                
            }
            catch {
                NotificationCenter.default.post(name:.oAuthDidFail, object: nil, userInfo: nil)
            }
        }
        
        task.resume()
        
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    // MARK: UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return posts.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)

        let post = self.posts[indexPath.row]
        
        let kind = post.first?.value as! String

        let data = post["data"] as! [String : AnyObject]

        print(data)

        
        
        
        
        // Configure the cell<commit_msg>basic cell attributes. Issue #5<commit_after>//
//  PostsCollectionViewController.swift
//  a-simple-reddit-client
//
//  Created by <NAME> on 08/02/17.
//  Copyright © 2017 mourodrigo. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class PostsCollectionViewController: UICollectionViewController {

    var posts: Array<[AnyHashable : AnyObject]> = []
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewDidAppear(_ animated: Bool) {
        fetchPosts()
    }
    
    func fetchPosts(){
     
        let url = URL(string: "https://www.reddit.com/top/.json")!
        let session = URLSession.shared
        
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        
        request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
        
        let task = session.dataTask(with: request) { ( data, response, error) in
            
            do {
                
                let JSONReturn = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [AnyHashable : AnyObject]
                
                self.posts = JSONReturn["data"]?["children"] as! Array<[String : AnyObject]>
                self.collectionView?.reloadData()
                
            }
            catch {
                NotificationCenter.default.post(name:.oAuthDidFail, object: nil, userInfo: nil)
            }
        }
        
        task.resume()
        
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    // MARK: UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return posts.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)

        let post = self.posts[indexPath.row]
        
        let kind = post.first?.value as! String

        let data = post["data"] as! [String : AnyObject]

        let author = data["author"]
        let title = data["title"]
        
        let date = data["created_utc"] //or created

        let numComments = data["num_comments"]
        
        
        print(data)

        
        
        
        
        // Configure the cell
{'fraction_non_alphanumeric': 0.08426884385478933, 'fraction_numerical': 0.003353258492491617, 'mean_word_length': 2.220657276995305, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 15, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, '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': '1121668', 'n_tokens_mistral': 1810, 'n_tokens_neox': 1731, 'n_words': 487}