//
//  GeoZoneModel.swift
//  Runner
//
//  Created by ZiKambrani on 13/12/2020.
//

import UIKit
import CoreLocation

class GeoZoneModel{
    var geofenceId:Int = -1
    var description:String = ""
    var descriptionN:String?
    var latitude:String?
    var longitude:String?
    var radius:Int?
    var type:Int?
    var projectID:Int?
    var imageURL:String?
    var isCity:String?
    
    func identifier() -> String{
        return "\(geofenceId)_hmg"
    }
    
    func message() -> String{
        return description
    }
    
    func toRegion(locationManager:CLLocationManager) -> CLCircularRegion?{
        if let rad = radius, let lat =  latitude?.removeSpace(), let long = longitude?.removeSpace(),
            let radius_d = Double("\(rad)"), let lat_d =  Double(lat), let long_d = Double(long){
            
            let coordinate = CLLocationCoordinate2D(latitude: lat_d, longitude: long_d)
            let validatedRadius = min(radius_d, locationManager.maximumRegionMonitoringDistance)
            
            let region = CLCircularRegion(center: coordinate, radius: validatedRadius, identifier: identifier())
            region.notifyOnExit = true
            region.notifyOnEntry = true
            return region
        }
        return nil
    }
    
    class func from(json:[String:Any]) -> GeoZoneModel{
        let model = GeoZoneModel()
        model.geofenceId = json["GEOF_ID"] as? Int ?? 0
        model.radius = json["Radius"] as? Int
        model.projectID = json["ProjectID"] as? Int
        model.type = json["Type"] as? Int
        model.description = json["Description"] as? String ?? ""
        model.descriptionN = json["DescriptionN"] as? String
        model.latitude = json["Latitude"] as? String
        model.longitude = json["Longitude"] as? String
        model.imageURL = json["ImageURL"] as? String
        model.isCity = json["IsCity"] as? String
        
        return model
    }
    
    class func list(from jsonString:String) -> [GeoZoneModel]{
        let value = dictionaryArray(from: jsonString)
        let geoZones = value.map { GeoZoneModel.from(json: $0) }
        return geoZones
    }
}
