//: A MapKit based Playground

import PlaygroundSupport
import AppKit
import Cocoa
import MapKit

private var artworks: [Artwork] = []
private var ports: [Port] = []
private var rightCalloutAccessoryView: [NSView]
public var nsg: [NSString]
//public var imageURL: [URL?]
//public var imageData: [Data]

// imageURL = [NSURL URLWithString:@"file:///Applications/MAMP/htdocs/swift_map_more-2.jpg"]
//let imageURL =
//NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first?.URLByAppendingPathComponent("swift_map_more-2.jpg")

class ViewController: NSViewController {

    @objc
    func printSomething() {
        print("Hello")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let myButtonRect = CGRect(x: 10, y: 10, width: 100, height: 10)
        let myButton =  NSButton(frame: myButtonRect)
        view.addSubview(myButton)

        myButton.target = self
        myButton.action = #selector(ViewController.printSomething)
    }

    //override var representedObject: AnyObject? {
    //    didSet {
        // Update the view, if already loaded.
    //    }
    // }
}

class ArtworkView: MKAnnotationView {
  override var annotation: MKAnnotation? {
    willSet {
      guard let artwork = newValue as? Artwork else {
        return
      }

      canShowCallout = true
      calloutOffset = CGPoint(x: -5, y: 5)
      let theButton: NSButton = NSButton()
          theButton.setButtonType(NSButton.ButtonType.pushOnPushOff)

          rightCalloutAccessoryView = theButton

      image = artwork.image
    }
  }
}

class ArtworkMarkerView: MKMarkerAnnotationView {
    override var annotation: MKAnnotation? {
    willSet {
      // 1
      var i = 22247
       guard let artwork = newValue as? Artwork else {
        return
      }
      canShowCallout = true
      calloutOffset = CGPoint(x: -5, y: 5)

      //rightCalloutAccessoryView = NSButton(type: .detailDisclosure)
      let mapsButton: NSButton = NSButton()
        mapsButton.setButtonType(NSButton.ButtonType.pushOnPushOff)
        // Insert code here to initialize your application
        //self.imageView.image = image;
        // initialise your image object with the image data
        //do {
        //    let imageData = try Data(contentsOf: imageURL)
        //    image = NSImage.init(data: imageData)
        //} catch {
        //    print("Unable to load data: \(error)")
        //}
        //image = NSImage.init(data: imageData)
        //mapsButton.setBackgroundImage(image, for: .normal)

        mapsButton.bezelStyle = .texturedSquare
        mapsButton.isBordered = false //Important
        mapsButton.wantsLayer = true
        mapsButton.layer?.backgroundColor = NSColor.systemPink.cgColor

        // rightCalloutAccessoryView = mapsButton
        
        
        // 2
      markerTintColor = artwork.markerTintColor
      if let letter = artwork.art_type?.first {
          if (letter == "M") {
          if let lettertwo = artwork.art_type {
          if (lettertwo == "Monument") {
          glyphText = "🏛️"
          } else {
          glyphText = "🎨"
          }
          } else {
          glyphText = String(letter)
          }
          } else if (letter == "P") {
          glyphText = "📛"
          } else if (letter == "A") {
          glyphText = "🖼️"
          } else if (letter == "S") {
          glyphText = "🗽"
          } else if (letter == "F") {
          glyphText = "⛲"
          } else {
          glyphText = String(letter)
          }
      }

      let detailLabel = NSTextField()
      //detailLabel.numberOfLines = 0
      //detailLabel.font = detailLabel.font.withSize(12)
      detailLabel.maximumNumberOfLines = 2
      detailLabel.stringValue = ""
      if (artwork.subtitle != nil) {
          detailLabel.stringValue = artwork.subtitle! }
        
      // detailCalloutAccessoryView = detailLabel
        
    }
  }
}

class Artwork: NSObject, MKAnnotation {
  let title: String?
  let locationName: String?
  let art_type: String?
  let coordinate: CLLocationCoordinate2D
  let image: NSImage?
    
  var markerTintColor: NSColor  {
      switch art_type {
      case "Monument":
        return .red
      case "Mural":
        return .cyan
      case "Plaque":
        return .blue
      case "Fountain":
        return .yellow
      case "Sculpture":
        return .purple
      case "Art":
        return .magenta
      default:
        return .green
      }
  }
    
  init(
    title: String?,
    locationName: String?,
    art_type: String?,
    coordinate: CLLocationCoordinate2D,
    image: NSImage?
  ) {
    self.title = title
    self.locationName = locationName
    self.art_type = art_type
    self.coordinate = coordinate
    self.image = nil

    super.init()
  }

    init?(feature: MKGeoJSONFeature) {
      // 1
      guard
        let point = feature.geometry.first as? MKPointAnnotation,
        let propertiesData = feature.properties,
        let json = try? JSONSerialization.jsonObject(with: propertiesData),
        let properties = json as? [String: Any]
        else {
          return nil
      }

      // 3
      title = properties["name"] as? String
      locationName = properties["descriptio"] as? String
      art_type = properties["art_type"] as? String
      coordinate = point.coordinate
      image =  nil
      super.init()
    }
    
  var subtitle: String? {
    return locationName
  }
}


class Port: NSObject, MKAnnotation {
  let title: String?
  let locationName: String?
  let port_type: String?
  let coordinate: CLLocationCoordinate2D
    
  var markerTintColor: NSColor  {
      switch port_type {
      case "Port":
        return .red
      default:
        return .green
      }
  }
    
  init(
    title: String?,
    locationName: String?,
    port_type: String?,
    coordinate: CLLocationCoordinate2D
  ) {
    self.title = title
    self.locationName = locationName
    self.port_type = port_type
    self.coordinate = coordinate

    super.init()
  }

    init?(feature: MKGeoJSONFeature) {
      // 1
      guard
        let point = feature.geometry.first as? MKPointAnnotation,
        let propertiesData = feature.properties,
        let json = try? JSONSerialization.jsonObject(with: propertiesData),
        let properties = json as? [String: Any]
        else {
          return nil
      }

      // 3
      title = properties["name"] as? String
      locationName = properties["website"] as? String
      port_type = properties["feature_class"] as? String
      coordinate = point.coordinate
      super.init()
    }
    
  var subtitle: String? {
    return locationName
  }
}


private func loadInitialData() {
  // 1
  guard
    let fileName = Bundle.main.url(forResource: "PublicArt", withExtension: "geojson"),
    let artworkData = try? Data(contentsOf: fileName)
    else {
     return
  }

  do {
    // 2
    let features = try MKGeoJSONDecoder()
      .decode(artworkData)
      .compactMap { $0 as? MKGeoJSONFeature }
    // 3
    let validWorks = features.compactMap(Artwork.init)
    // 4
    artworks.append(contentsOf: validWorks)
  } catch {
    // 5
    print("Unexpected error: \(error).")
  }
}

private func loadNextData() {
  // 1
  guard
    let fileName = Bundle.main.url(forResource: "map", withExtension: "geojson"),
    let portData = try? Data(contentsOf: fileName)
    else {
     return
  }

  do {
    // 2
    let features = try MKGeoJSONDecoder()
      .decode(portData)
      .compactMap { $0 as? MKGeoJSONFeature }
    // 3
    let validWorks = features.compactMap(Port.init)
    // 4
    ports.append(contentsOf: validWorks)
  } catch {
    // 5
    print("Unexpected error: \(error).")
  }
}

let chatswoodCoordinates = CLLocationCoordinate2DMake(-33.8009948,151.1664372)

// Now let's create a MKMapView
let mapView = MKMapView(frame: CGRect(x:0, y:0, width:800, height:800))

// Define a region for our map view
var mapRegion = MKCoordinateRegion()

let mapRegionSpan = 0.001
mapRegion.center = chatswoodCoordinates
mapRegion.span.latitudeDelta = mapRegionSpan
mapRegion.span.longitudeDelta = mapRegionSpan

mapView.setRegion(mapRegion, animated: true)

// Create a map annotation
let annotation = MKPointAnnotation()
annotation.coordinate = chatswoodCoordinates
annotation.title = "Chatswood"
annotation.subtitle = "Greville"

mapView.addAnnotation(annotation)

// Show artwork on map
let artwork = Artwork(
  title: "The Cheesetree",
  locationName: "Santa Clause Lane",
  art_type: "Nature, like",
  coordinate: CLLocationCoordinate2D(latitude: -33.8010376, longitude: 151.1663819),
  image: nil)

mapView.addAnnotation(artwork)

loadInitialData()
mapView.addAnnotations(artworks)

loadNextData()
mapView.addAnnotations(ports)

mapView.register(
  ArtworkMarkerView.self,
  forAnnotationViewWithReuseIdentifier:
    MKMapViewDefaultAnnotationViewReuseIdentifier)

// Add the created mapView to our Playground Live View
PlaygroundPage.current.liveView = mapView



