//
//  WiFiPointsViewController.swift
//  kt
//
//  Created by Alexandr Zalutskiy on 28.01.15.
//  Copyright (c) 2015 Alexandr Zalutskiy. All rights reserved.
//

import UIKit
import MapKit


protocol WayProtocol {
  func setWayToLocation(location : CLLocation)
  func getDirections(destination: CLLocationCoordinate2D)
}

func _regionForCoordinate(coordinate: CLLocationCoordinate2D) -> MKCoordinateRegion {
  return MKCoordinateRegion(center: coordinate, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
}

func cityForCoordinate(coordinate: CLLocationCoordinate2D) -> MKCoordinateRegion {
  return MKCoordinateRegion(center: coordinate, span: MKCoordinateSpan(latitudeDelta: 0.4, longitudeDelta: 0.4))
}

extension UINavigationController {
    func WhiteLabel() {
        for var view in (self.navigationBar.subviews) {
            if (view.isKindOfClass(UILabel)) {
                let label = view as! UILabel
                label.textColor = UIColor.whiteColor()
            }
        }
    }
}

class WiFiPointsViewController : ViewControllerWithMenu {
  
    var locationManager = CLLocationManager()
  @IBOutlet private weak var wifiMapView : MKMapView!
  @IBOutlet private weak var standardButton: UIButton!
  @IBOutlet private weak var hybridButton: UIButton!
  @IBOutlet private weak var satelliteButton: UIButton!
  
  var destination: MKMapItem?
  private let notificationCenter = NSNotificationCenter.defaultCenter()
  private let facade = Facade.sharedInstance()
  private var wifiPoints: [WiFi]?
  private let annotationViewIdentifier = "wifiAnnotation"
  
  // MARK: View life cycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.requestAlwaysAuthorization()
    configureRightIndicator()
    self.navigationItem.title = LocalizedString("menu.wifi-points", description: "Точки Wi-Fi")
    loadingIndicator!.startAnimating()
    //configureBlueNavbar()
    registerForWiFiPoints()
    facade.getWiFiPointsForCity(CitiesManager.sharedInstance().userCity())
    wifiMapView.mapType = .Standard
  }
  
  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()
  }
  
  // MARK: Notifications
  
  private func registerForWiFiPoints() {
    notificationCenter.addObserver(self, selector: #selector(WiFiPointsViewController.setWiFiPoints(_:)),
                                   name: FacadeWiFiPointsSuccess, object: facade)
  }
  
  private func unregisterForWiFiPoints() {
    notificationCenter.removeObserver(self, name: FacadeWiFiPointsSuccess, object: facade)
  }
  
  // MARK: Facade observering
  
  func setWiFiPoints(notification: NSNotification) {
    loadingIndicator!.stopAnimating()
    showListButton()
    
    unregisterForWiFiPoints()
    let points = notification.userInfo!["points"] as! [WiFi]
    
    wifiMapView.showAnnotations(points, animated: true)
    wifiPoints = points
    self.wifiMapView.addAnnotations(points)
    
    
    
    
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = kCLLocationAccuracyKilometer
    locationManager.startUpdatingLocation()
    var location = locationManager.location
    var coordinate = location?.coordinate
    
    if (coordinate != nil) {
        wifiMapView.setCenterCoordinate(coordinate!, animated: true)
        wifiMapView.region = MKCoordinateRegionMakeWithDistance(coordinate!, 1000, 1000)
    }
  }
  
  // MARK: - public actions
  
  func setCoordinate(coordinate: CLLocationCoordinate2D) {
    // TODO: ====
    wifiMapView.region = _regionForCoordinate(coordinate)
  }
  
  // MARK: - Helper
  
  func showListButton() {
    let button = UIButton(frame: CGRect(x: -10, y: 0, width: 32, height: 32))
    button.setImage(UIImage(named: "map_address_icon_highlighted"), forState: .Normal)
    // FIXME: cahnge image color
    button.setImage(UIImage(named: "map_address_icon"), forState: .Highlighted)
    button.addTarget(self, action: #selector(WiFiPointsViewController.showWiFiList(_:)), forControlEvents: .TouchUpInside)    
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
  }
  
  func showWiFiList(sender: UIButton) {
    let vc = storyboard!.instantiateViewControllerWithIdentifier("WiFiTableViewController") as! WiFiTableViewController
    vc.wifiPoints = wifiPoints
    vc.pvc = self
    let nvc = UINavigationController(rootViewController: vc)
    presentViewController(nvc, animated: true, completion: nil)
  }
  
  // MARK: - Actions
  
  @IBAction func standardButton_TouchUpInside(sender: UIButton?) {
    self.wifiMapView.mapType = .Standard
    selectButton(standardButton)
  }
  
  @IBAction func hybridButton_TouchUpInside(sender: UIButton?) {
    self.wifiMapView.mapType = .Hybrid
    selectButton(hybridButton)
  }
  
  @IBAction func satelliteButton_TouchUpInside(sender: UIButton?) {
    self.wifiMapView.mapType = .Satellite
    selectButton(satelliteButton)
  }
  
  private func selectButton(button: UIButton) {
    standardButton.selected = false
    hybridButton.selected = false
    satelliteButton.selected = false
    
    button.selected = true
  }
  
  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showInfo" {
      let dvc = segue.destinationViewController as! MapPointInfoController
      dvc.mapViewController = self
      dvc.point = sender as! MKAnnotation
    }
  }
}

// MARK: - MKMapViewDelegate
extension WiFiPointsViewController: MKMapViewDelegate {
  
  func showRoute(response: MKDirectionsResponse) {
    
    for route in response.routes {
      
      wifiMapView.addOverlay(route.polyline,
                             level: MKOverlayLevel.AboveRoads)
      
      for step in route.steps {
        print(step.instructions)
      }
    }
    let userLocation = wifiMapView.userLocation
    let region = MKCoordinateRegionMakeWithDistance(
      userLocation.location!.coordinate, 2000, 2000)
    
    wifiMapView.setRegion(region, animated: true)
  }
  
  func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation.isKindOfClass(MKUserLocation) {
      return nil
    }
    var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(annotationViewIdentifier)
    if annotationView != nil {
      annotationView!.annotation = annotation
    } else {
      annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: annotationViewIdentifier)
      annotationView!.canShowCallout = true
      
      let button = UIButton(type: .InfoLight) as UIButton
      button.addTarget(nil, action: nil, forControlEvents: .TouchUpInside)
      
      annotationView!.rightCalloutAccessoryView = button
    }
    
    return annotationView
  }
  
  func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    performSegueWithIdentifier("showInfo", sender: view.annotation)
  }
  
  func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
    
    if overlay is MKPolyline {
      let pr = MKPolylineRenderer(overlay: overlay)
      pr.strokeColor = Color.BlueColorForHighlighted
      pr.fillColor = Color.BlueColorForHighlighted
      pr.lineWidth = 3
      return pr
    }
    
    return MKPolylineRenderer(overlay: overlay)
  }
}

extension WiFiPointsViewController: WayProtocol {
  func setWayToLocation(location: CLLocation) {
    
  }
  
  func getDirections(location: CLLocationCoordinate2D){
    // Coordinates for simplecode - latitude: 49.803455, longitude: 73.085145
    let destlocation = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
    let mapManager = MapManager()
    if let sourceLocation = LocationManager().location?.coordinate {
      mapManager.directionsUsingGoogle(from: sourceLocation, to: destlocation) { (route, directionInformation, boundingRegion, error) -> () in
        
        if let error = error {
          print(error)
        } else {
          if let web = self.wifiMapView {
            dispatch_async(dispatch_get_main_queue()) {
              web.removeOverlays(web.overlays)
              web.addOverlay(route!)
              web.setVisibleMapRect(boundingRegion!, animated: true)
            }
          }
        }
      }
    } else {
      AlertViewUtil.showErrorAlert(LS("error"), message: LS("wifi_points.unavailable_current_location"))
    }
    
  }
  
}

extension WiFiPointsViewController {
  override var localizedId: String {
    return "wifi_points"
  }
}
