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

import UIKit
import MapKit

class PssPointsViewController : ViewControllerWithMenu, MKMapViewDelegate {
  
  @IBOutlet private weak var standardButton: UIButton!
  @IBOutlet private weak var hybridButton: UIButton!
  @IBOutlet private weak var satelliteButton: UIButton!
  @IBOutlet private weak var pssMapView : MKMapView!
  
  private let notificationCenter = NSNotificationCenter.defaultCenter()
  private let facade = Facade.sharedInstance()
  private let annotationViewIdentifier = "pssAnnotation"
  private var pssPoints: [Pss]?
  
  // MARK: View life cycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    configureRightIndicator()
    self.navigationItem.title = LocalizedString("menu.service-points", description: "Пункты сети сервиса")
    
    //    configureRightIndicator()
    loadingIndicator!.startAnimating()
    
    registerForPssPoints()
    facade.getPssPointsForCity(CitiesManager.sharedInstance().userCity())
    pssMapView.mapType = .Standard
    
    //		pssMapView.userInteractionEnabled = true
    
  }
  
  override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    
    //    standardButton.setTitle(LocalizedString("map.standard", description: "Standard"), forState: .Normal)
    //    hybridButton.setTitle(LocalizedString("map.hybrid", description: "Hybrid"), forState: .Normal)
    //    satelliteButton.setTitle(LocalizedString("map.satellite", description: "Satellite"), forState: .Normal)
  }
  
  // MARK: Notifications
  
  private func registerForPssPoints() {
    notificationCenter.addObserver(
      self,
      selector: #selector(PssPointsViewController.setPssPoints(_:)),
      name: FacadePssPointsSuccess,
      object: facade
    )
  }
  
  private func unregisterForPssPoints() {
    notificationCenter.removeObserver(self, name: FacadePssPointsSuccess, object: facade)
  }
  
  // MARK: Facade observering
  
  func setPssPoints(notification: NSNotification) {
    loadingIndicator!.stopAnimating()
    showListButton()
    
    unregisterForPssPoints()
    let points = notification.userInfo!["points"] as! [Pss]
    
    pssMapView.showAnnotations(points, animated: true)
    
    pssPoints = points
    self.pssMapView.addAnnotations(points)
  }
  
  // MARK: - public actions
  func _regionForCoordinate(coordinate: CLLocationCoordinate2D) -> MKCoordinateRegion {
    return MKCoordinateRegion(center: coordinate, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
  }
  
  func setCoordinate(coordinate: CLLocationCoordinate2D) {
    pssMapView.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"), forState: .Normal)
    // FIXME: cahnge image color
    button.setImage(UIImage(named: "map_address_icon_highlighted"), forState: .Highlighted)
    button.addTarget(self, action: #selector(PssPointsViewController.showWiFiList(_:)), forControlEvents: .TouchUpInside)
    
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
  }
  
  func showWiFiList(sender: UIButton?) {
    let vc = storyboard!.instantiateViewControllerWithIdentifier("PssTableViewController")
      as! PssTableViewController
    vc.pssPoints = pssPoints
    vc.pvc = self
    let nvc = UINavigationController(rootViewController: vc)
    presentViewController(nvc, animated: true, completion: nil)
  }
  
  
  // MARK: - Actions
  
  //  @IBAction func standardButton_TouchUpInside(sender: UIButton?) {
  //    self.pssMapView.mapType = .Standard
  //    selectButton(standardButton)
  //  }
  //
  //  @IBAction func hybridButton_TouchUpInside(sender: UIButton?) {
  //    self.pssMapView.mapType = .Hybrid
  //    selectButton(hybridButton)
  //  }
  //
  //  @IBAction func satelliteButton_TouchUpInside(sender: UIButton?) {
  //    self.pssMapView.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 PssPointsViewController {
  
  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 PssPointsViewController: WayProtocol {
  func setWayToLocation(location: CLLocation) {
    
    //    let response = pathAction {
    //      self.pssMapView.removeOverlays(self.pssMapView.overlays)
    //      let polyline = MKPolyline.polylineWithEncodedString($0)
    //      self.pssMapView.addOverlay(polyline, level: .AboveRoads)
    //    }
    //
    //    _routeFromPoint(location.coordinate, LocationManager.sharedInstance().location!.coordinate) <*> response
  }
  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.pssMapView{
            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("pss_points.unavailable_current_location"))
    }
  }
}

extension PssPointsViewController {
  override var localizedId: String {
    return "pss_points"
  }
}
