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

import UIKit
import CoreLocation

class PssTableViewController: ViewControllerWithCustomTitle {
	
	@IBOutlet private weak var tableView: UITableView!

	
	var pssPoints: [Pss]? {
		didSet {
			if let userLocarion = LocationManager.sharedInstance().location {
				if let pssPoints = pssPoints {
					for point in pssPoints {
						let coordinate = point.coordinate
						point.distance = Int(userLocarion.distanceFromLocation(CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)))
					}
				}
			}
			
			if pssPoints != nil {
				pssPoints!.sortInPlace {
					$0.distance < $1.distance
				}
			}
		}
	}
	
	var pvc: PssPointsViewController?
	
	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(Color.DarkColorForText, 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(PssTableViewController.hide(_:)), forControlEvents: .TouchUpInside)
		
		navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
	}
	
	func hide(sender: AnyObject?) {
		dismissViewControllerAnimated(true, completion: nil)
	}
}

// MARK: - UITableViewDataSource
extension PssTableViewController: UITableViewDataSource {
	func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		if let pssPoints = pssPoints {
			return pssPoints.count
		}
		return 0
	}
	
	func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
		let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as UITableViewCell
		cell.textLabel?.text = pssPoints?[indexPath.row].title
//        cell.titleLabel.text = pssPoints?[indexPath.row].title
//        cell.subTitleLabel.text = pssPoints?[indexPath.row].address
        cell.detailTextLabel?.text = pssPoints?[indexPath.row].address
		if let _ = LocationManager.sharedInstance().location,
			let _ = pssPoints?[indexPath.row].coordinate  {
				let distance = pssPoints![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 PssTableViewController: UITableViewDelegate {
	func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
		let text = pssPoints![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 = pssPoints?[indexPath.row].coordinate {
			pvc?.setCoordinate(coordinate)
			dismissViewControllerAnimated(true, completion: nil)
		}
        
	}
}
