 import UIKit
 import MapKit
 import Parse
+import PureLayout
 
 private enum EmptyListLabelText: String {
     case Loading = "Loading...",

    private var searchDistance: CLLocationDistance = 500
    
    let tableHeaderLabel: UILabel = UILabel()
    
    // MARK - View cycle 
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.estimatedRowHeight = 120
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.tableHeaderView = tableHeaderLabel
        tableHeaderLabel.contentMode = UIViewContentMode.Top
        tableHeaderLabel.textAlignment = NSTextAlignment.Center
        // register table cell classes
        let classesToRegister = [BRCEventObject.self, BRCDataObject.self]
        for objClass in classesToRegister {
            let cellClass: (AnyClass!) = BRCDataObjectTableViewCell.cellClassForDataObjectClass(objClass)
            let nib = UINib(nibName: NSStringFromClass(cellClass), bundle: nil)
            let reuseIdentifier = cellClass.cellIdentifier()
            self.tableView!.registerNib(nib, forCellReuseIdentifier: reuseIdentifier)
        }
        self.tableView.registerClass(SubtitleCell.self, forCellReuseIdentifier: SubtitleCell.kReuseIdentifier)
    }
    
    func getCurrentLocation() -> CLLocation {
        let appDelegate = BRCAppDelegate.sharedAppDelegate()
        let currentLocation = appDelegate.locationManager.location
        return currentLocation
    }
    
    func refreshNearbyItems() {
        let currentLocation = getCurrentLocation()
        let region = MKCoordinateRegionMakeWithDistance(currentLocation.coordinate, searchDistance, searchDistance)
        BRCDatabaseManager.sharedInstance().queryObjectsInRegion(region, completionQueue: dispatch_get_main_queue(), resultsBlock: { (results: [AnyObject]!) -> Void in
            // TODO: Filter & sort items
            let nearbyObjects = results as! [BRCDataObject]
            let options = BRCDataSorterOptions()
            BRCDataSorter.sortDataObjects(nearbyObjects, options: options, completionQueue: dispatch_get_main_queue(), callbackBlock: { (events, art, camps) -> (Void) in
                var sections: [TableViewSection] = []
                if events.count > 0 {
                    let eventsSection = TableViewSection(objects: events, sectionTitle: ObjectType.Events)
                    sections.append(eventsSection)
                }
                if art.count > 0 {
                    let artSection = TableViewSection(objects: art, sectionTitle: ObjectType.Art)
                    sections.append(artSection)
                }
                if camps.count > 0 {
                    let campsSection = TableViewSection(objects: camps, sectionTitle: ObjectType.Camps)
                    sections.append(campsSection)
                }
                self.sections = sections
                if BRCDatabaseManager.sharedInstance().rTreeIndex != nil {
                    self.emptyListText = EmptyListLabelText.Nothing
                }
                self.tableView.reloadData()
            })
        })
    }
    
    func refreshHeaderLabel() {
        let labelText: NSMutableAttributedString = NSMutableAttributedString()
        let font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
        let attributes: [String: AnyObject] = [NSFontAttributeName: font]
        labelText.appendAttributedString(NSAttributedString(string: "Within ", attributes: attributes))
        labelText.appendAttributedString(TTTLocationFormatter.brc_humanizedStringForDistance(searchDistance))
        tableHeaderLabel.attributedText = labelText
        tableHeaderLabel.sizeToFit()
        let labelFrame = tableHeaderLabel.frame
        tableHeaderLabel.frame = CGRectMake(labelFrame.origin.x, labelFrame.origin.y, labelFrame.size.width, labelFrame.size.height + 16)
        tableView.tableHeaderView = tableHeaderLabel
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        PFAnalytics.trackEventInBackground("Nearby", block: nil)
        refreshHeaderLabel()
        refreshNearbyItems()
        let location = BRCAppDelegate.sharedAppDelegate().locationManager.location
        BRCGeocoder.sharedInstance().asyncReverseLookup(location.coordinate, completionQueue: dispatch_get_main_queue()) { (locationString: String!) -> Void in

        return cell
    }
    
    // MARK: - UITableViewDelegate
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if !hasNearbyObjects() {
            return
        }
        let dataObject = sections[indexPath.section].objects[indexPath.row]
        let detailVC = BRCDetailViewController(dataObject: dataObject)
        navigationController!.pushViewController(detailVC, animated: true)
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
    
}
