//
//  MKPolyline+EncodedString.swift
//  kt
//
//  Created by Alexander Zalutskiy on 25.02.15.
//  Copyright (c) 2015 Alexandr Zalutskiy. All rights reserved.
//

import MapKit
import Darwin

extension MKPolyline {
  class func polylineWithEncodedString(encodedString: String) -> MKPolyline {
    var poly = [CLLocationCoordinate2D]()
    _ = encodedString.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
    var lat = 0, lng = 0
    
    let encoded = encodedString.utf8
    
    var index = encoded.startIndex
    
    while index != encoded.endIndex {
      var b: Int, shift = 0, result = 0
      repeat {
        b = Int(encoded[index]) - 63;
        index = index.successor()
        result |= (b & 0x1f) << (shift % 32)
        shift += 5;
      } while (b >= 0x20);
      let dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1))
      lat += dlat;
      
      shift = 0;
      result = 0;
      repeat {
        b = Int(encoded[index]) - 63;
        index = index.successor()
        result |= (b & 0x1f) << (shift % 32)
        shift += 5;
      } while (b >= 0x20);
      let dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
      lng += dlng;
      
      let p = CLLocationCoordinate2D(latitude: Double(lat) / 1E5, longitude: Double(lng) / 1E5)
      poly.append(p);
    }
    
    for coord in poly {
      print("\(coord.latitude),\(coord.longitude)")
    }
    
    
    let polyline = MKPolyline(coordinates: &poly, count: poly.count)
    print(polyline.pointCount)
    return polyline
  }
}
