//
//  WiFiTableViewController.swift
//  kt
//
//  Created by Alexander Zalutskiy on 24.02.15.
//  Copyright (c) 2015 Alexandr Zalutskiy. All rights reserved.
//

import UIKit
import CoreLocation

class WiFiTableViewController: ViewControllerWithCustomTitle {
	
	@IBOutlet private weak var tableView: UITableView!
	
	var wifiPoints: [WiFi]? {
		didSet {
			if let userLocarion = LocationManager.sharedInstance().location {
				if let wifiPoints = wifiPoints {
					for point in wifiPoints {
						let coordinate = point.coordinate
						point.distance = Int(userLocarion.distanceFromLocation(CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)))
					}
				}
			}
			
			if wifiPoints != nil {
				wifiPoints?.sortInPlace {
					$0.distance < $1.distance
				}
			}
		}
	}
	
	
	var pvc: WiFiPointsViewController?
	
	private let cellIdentifier = "wifiPoint"
	
	override func viewDidLoad() {
		super.viewDidLoad()
		
		navigationBarTitle = LocalizedString("map.address", description: "Адреса")
		
		let backButton = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 40))
		backButton.setTitle(LocalizedString("back", description: LS("back")), forState: .Normal)
		backButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
		backButton.setTitleColor(Color.BlueColorForHighlighted, forState: .Highlighted)
		backButton.titleLabel!.font = UIFont(name: "PTSans-Regular", size: 17)
		backButton.titleLabel?.textAlignment = .Right
		backButton.addTarget(self, action: #selector(WiFiTableViewController.hide(_:)), forControlEvents: .TouchUpInside)
		
        self.navigationController?.WhiteLabel()
		navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
        
	}
	
    override func configureBlueNavbar() {
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        self.navigationController?.navigationBar.barTintColor = Color.DashboardBlueColor
        self.navigationController?.navigationBar.barStyle = UIBarStyle.Black
        //    self.navigationController?.navigationBar.tintColor = nil
        self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
        
        navigationController?.navigationBar.setBottomBorderColor(UIColor.whiteColor(), height: 0)
        self.navigationController?.navigationBar.translucent = false
        self.navigationItem.titleView?.tintColor = UIColor.whiteColor()
        
        self.navigationController?.WhiteLabel()       
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        configureBlueNavbar()
    }

    
    
	func hide(sender: AnyObject?) {
		dismissViewControllerAnimated(true, completion: nil)
	}
}

// MARK: - UITableViewDataSource
extension WiFiTableViewController: UITableViewDataSource {
	func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		if let wifiPoints = wifiPoints {
			return wifiPoints.count
		}
		return 0
	}
	
	func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        print(indexPath.row)
		let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as UITableViewCell
		cell.textLabel?.text = wifiPoints?[indexPath.row].title
//        cell.titleLabel.text = wifiPoints?[indexPath.row].title
//        cell.subTitleLabel.text = wifiPoints?[indexPath.row].address
        cell.detailTextLabel?.text = wifiPoints?[indexPath.row].address
		if let _ = LocationManager.sharedInstance().location,
			let _ = wifiPoints?[indexPath.row].coordinate  {
				let distance = wifiPoints![indexPath.row].distance!
				
				let (km, m) = convertDistance(distance)
				
				if km > 0 {
					cell.detailTextLabel?.text = "\(km) км., "
				} else {
					cell.detailTextLabel?.text = ""
				}
				cell.detailTextLabel?.text = cell.detailTextLabel!.text! + "\(m) м."
		}
		
		
		let selectedView = UIView(frame: cell.contentView.frame)
		selectedView.backgroundColor = Color.BlueColorForHighlighted
		cell.selectedBackgroundView = selectedView
		//cell.selectionStyle = .None
		return cell
	}
}

extension WiFiTableViewController: UITableViewDelegate {
	func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
		let text = wifiPoints![indexPath.row].title
		let attributes = [NSFontAttributeName: UIFont(name: "PTSans-Bold", size: 17.0)!]// as [NSObject: AnyObject]
		return text!.boundingRectWithSize(CGSize(width: tableView.frame.width - 30.0, height: CGFloat.max),
			options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil).height + 38.0
	}
	
	func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
		if let coordinate = wifiPoints?[indexPath.row].coordinate {
			pvc?.setCoordinate(coordinate)
			dismissViewControllerAnimated(true, completion: nil)
		}
	}
}
