import MapplsDirectionUI
import MapplsUIWidgets
import MapplsAPIKit
import React
import MapplsNearbyUI

@objc(MapplsDirectionWidgetReactNative)
class MapplsDirectionWidgetReactNative: NSObject, MapplsDirectionViewControllerDelegate {
    
    
    private var  resolver: RCTPromiseResolveBlock?
    private var  rejecter: RCTPromiseRejectBlock?
    
    
    //required for exporting constants
    @objc
    static func requiresMainQueueSetup() -> Bool {
        return true
    }
    
    
    //exporting constants
    @objc func constantsToExport() -> NSObject {
        return [
            
            //profile
            "PROFILE_DRIVING_KEY": MapplsDirectionsProfileIdentifier.driving,
            "PROFILE_WALKING_KEY": MapplsDirectionsProfileIdentifier.walking,
            "PROFILE_BIKING_KEY": MapplsDirectionsProfileIdentifier.biking,
            "PROFILE_TRUCKING_KEY": MapplsDirectionsProfileIdentifier.trucking,
            
            //resources
            "RESOURCE_ADV_KEY":MapplsDirectionsResourceIdentifier.routeAdv,
            "RESOURCE_ETA_KEY":MapplsDirectionsResourceIdentifier.routeETA,
            "RESOURCE_TRAFFIC_KEY":MapplsDirectionsResourceIdentifier.routeTraffic,
            
            
            //Overview
            "OVERVIEW_FULL_KEY": RouteShapeResolution.full.rawValue,
            "OVERVIEW_FALSE_KEY": RouteShapeResolution.none.rawValue,
            "OVERVIEW_SIMPLIFIED_KEY": RouteShapeResolution.low.rawValue,
            
            //attributions
            "ATTRIBUTIONS_CONGESTION_KEY": AttributeOptions.congestionLevel.rawValue,
            "ATTRIBUTIONS_DISTANCE_KEY": AttributeOptions.distance.rawValue,
            "ATTRIBUTIONS_SPEED_KEY": AttributeOptions.speed.rawValue,
            "ATTRIBUTIONS_DURATION_KEY":AttributeOptions.expectedTravelTime.rawValue,
            
            
            
            //PlaceOptions
            
            //Pods
            "POD_SUB_LOCALITY_KEY" : MapplsPodType.sublocality,
            "POD_LOCALITY_KEY": MapplsPodType.locality,
            "POD_CITY_KEY" : MapplsPodType.city,
            "POD_VILLAGE_KEY" : MapplsPodType.village,
            "POD_SUB_DISTRICT_KEY":MapplsPodType.subdistrict,
            "POD_DISTRICT_KEY": MapplsPodType.district,
            "POD_STATE_KEY" : MapplsPodType.state,
            "POD_SUB_SUB_LOCALITY_KEY": MapplsPodType.subSubLocality,
            
            //attributionHorizontalAlignment
            "GRAVITY_LEFT_KEY": MapplsHorizontalContentAlignment.left.rawValue,
            "GRAVITY_CENTER_KEY": MapplsHorizontalContentAlignment.center.rawValue,
            "GRAVITY_RIGHT_KEY": MapplsHorizontalContentAlignment.right.rawValue,
            
            //attributionVerticalAlignment
            "GRAVITY_TOP_KEY": MapplsVerticalPlacement.before.rawValue,
            "GRAVITY_BOTTOM_KEY":MapplsVerticalPlacement.after.rawValue,
            
            //logoSize
            "SIZE_SMALL_KEY": MapplsContentSize.small.rawValue,
            "SIZE_MEDIUM_KEY":MapplsContentSize.medium.rawValue,
            "SIZE_LARGE_KEY":MapplsContentSize.large.rawValue,
            
        ] as NSObject
    }
    
    @objc(openDirectionWidget:withResolver:withRejecter:)
    func openDirectionWidget(params:NSDictionary,  resolve:@escaping RCTPromiseResolveBlock,reject:@escaping RCTPromiseRejectBlock) -> Void {
        
        DispatchQueue.main.async {
            
            self.resolver = resolve
            self.rejecter = reject
            
            var locationModels = [MapplsDirectionLocation]()
            
            if params["source"] != nil {
                let sourceLocation = self.addDirectionLocations(dictionary: params, key: "source",locationType:.current)
                if sourceLocation != nil {
                    locationModels.append(sourceLocation!)
                }
                
            }
            
            if params["destination"] != nil {
                let destinationLocation = self.addDirectionLocations(dictionary: params, key: "destination",locationType:.suggestion)
                if destinationLocation != nil {
                    locationModels.append(destinationLocation!)
                }
                
            }
            
            
            
            let directionVC = MapplsDirectionViewController(for: locationModels)
            directionVC.modalPresentationStyle = .fullScreen
            
            directionVC.delegate = self
            
            if params["profile"] != nil {
                let mProfile = params["profile"] as! String
                
                if mProfile == MapplsDirectionsProfileIdentifier.walking.rawValue||mProfile == MapplsDirectionsProfileIdentifier.trucking.rawValue {
                    
                    directionVC.attributationOptions = []
                }
                directionVC.profileIdentifier = MapplsDirectionsProfileIdentifier(mProfile)
                
            }
            
            if params["resource"] != nil {
                let mResource = params["resource"] as! String
                directionVC.resourceIdentifier = MapplsDirectionsResourceIdentifier(mResource)
            }
            
            if params["showAlternative"] != nil {
                let mShowAlternative = params["showAlternative"] as! Bool
                directionVC.isIncludesAlternativeRoutes = mShowAlternative
            }
            
            if params["attributions"] != nil {
                let mAttributions = params["attributions"] as! [String]
                directionVC.attributationOptions = AttributeOptions.init(descriptions: mAttributions)!
                
            }
            
            if params["showStartNavigation"] != nil {
                let mShowStartNavigation = params["showStartNavigation"] as! Bool
                directionVC.isShowStartNavigation = mShowStartNavigation
            }
            if params["steps"] != nil {
                let steps = params["steps"] as! Bool
                directionVC.includesSteps = steps
            }
            
            if params["overview"] != nil {
                let mOverView = params["overview"] as! UInt
                directionVC.routeShapeResolution = RouteShapeResolution(rawValue:mOverView)!
                
            }
            
            if params["excludes"] != nil {
                let excludes = params["excludes"] as! [String]
                directionVC.excludeOptions = MapplsExcludeOptions(descriptions: excludes)!
                //only for android
            }
            if params ["showProfileOption"] != nil {
                
            }
            if params["searchAlongRoute"] != nil {
                let searchAlongRoute = params["searchAlongRoute"] as! Bool
                directionVC.isShowSearchAlongRoute = searchAlongRoute
            }
            if params["alongRouteBuffer"] != nil {
                let alongRouteBuffer = params["alongRouteBuffer"] as! Int
                directionVC.nearbyPOIBuffer = alongRouteBuffer
            }
            
            if params["categoryCodes"] != nil {
                let categoryCodesList = self.toCategoryCodes(categories: params["categoryCodes"] as! [NSDictionary])
                directionVC.mapplsPOISearchCategory = categoryCodesList
            }
            
            if params["selectedRouteColor"] != nil {
                
            }
            
            if params["selectedCasingRouteColor"] != nil {
                
            }
            
            if params["alternateRouteColor"] != nil {
                
            }
            
            if params["alternateCasingRouteColor"] != nil {
                
            }
            
            if params["showAddWaypointOption"] != nil {
                let showAddWaypointOption = params["showAddWaypointOption"] as! Bool
                directionVC.shouldAllowToAddViapoint = showAddWaypointOption
            }
            
            if params["showRouteReportSummary"] != nil {
                let showRouteReportSummary = params["showRouteReportSummary"] as! Bool
                MapplsDirectionUIConfiguration.shared.shouldShowRouteReportSummary = showRouteReportSummary
            }
            
            if params["showRouteReportSummaryOnMap"] != nil {

            }
            
            if params["showTripCostSummary"] != nil {
                let showTripCostSummary = params["showTripCostSummary"] as! Bool
                MapplsDirectionUIConfiguration.shared.shouldShowTollCostEstimation = showTripCostSummary
            }
            
            if params["searchPlaceOption"] != nil {
                let mSearchPlaceOptions = params["searchPlaceOption"] as! NSDictionary
                
                
                //Not for ios
                if mSearchPlaceOptions["historyCount"] != nil {
                     let historyCount=mSearchPlaceOptions["historyCount"] as! Int
                     HistoryCountToShow = historyCount
                }
                
                //yet not availble for ios
                if mSearchPlaceOptions["saveHistory"] != nil {
                    let mSaveHistory=mSearchPlaceOptions["saveHistory"] as! Bool
                     IsHistoryEnabled=true
                }
                if mSearchPlaceOptions["backgroundColor"] != nil {
                    let mBackgroundColor = mSearchPlaceOptions["backgroundColor"] as! String
                    directionVC.autocompleteViewController.tableCellBackgroundColor = self.colorWithHexString(hexString: mBackgroundColor)
                }
                
                if mSearchPlaceOptions["toolbarColor"] != nil {
                    let mToolbarColor = mSearchPlaceOptions["toolbarColor"] as! String
                    UINavigationBar.appearance(whenContainedInInstancesOf: [MapplsAutocompleteViewController.self]).barTintColor=self.colorWithHexString(hexString: mToolbarColor)
                } else {
                    UINavigationBar.appearance(whenContainedInInstancesOf: [MapplsAutocompleteViewController.self]).barTintColor=self.colorWithHexString(hexString: "#FFFFFF")
                }
                
                if mSearchPlaceOptions["hint"] != nil {
                }
                
                
                if mSearchPlaceOptions["attributionVerticalAlignment"] != nil {
                    let attributionVerticalAlignment = mSearchPlaceOptions["attributionVerticalAlignment"] as! Int
                    directionVC.autocompleteViewController.attributionSettings.attributionVerticalPlacement = MapplsVerticalPlacement(rawValue: attributionVerticalAlignment)!
                    
                }
                
                if mSearchPlaceOptions["attributionHorizontalAlignment"] != nil {
                    let attributionHorizontalAlignment = mSearchPlaceOptions["attributionHorizontalAlignment"] as! Int
                    directionVC.autocompleteViewController.attributionSettings.attributionHorizontalContentAlignment = MapplsHorizontalContentAlignment(rawValue: attributionHorizontalAlignment)!
                }
                
                if mSearchPlaceOptions["logoSize"] != nil {
                    let logoSize = mSearchPlaceOptions["logoSize"] as! Int
                    directionVC.autocompleteViewController.attributionSettings.attributionSize = MapplsContentSize(rawValue: logoSize)!
                    
                }
                if mSearchPlaceOptions["enableTextSearch"] != nil {
                    let enableTextSearch = mSearchPlaceOptions["enableTextSearch"] as! Bool
                    IsTextSearchEnabledOnPressingEnterOrSearchKey = enableTextSearch
                }
                
                if mSearchPlaceOptions["showPoweredByText"] != nil {
                    let showPoweredByText = mSearchPlaceOptions["showPoweredByText"] as! Bool
                    
                    if showPoweredByText {
                        directionVC.autocompleteViewController.attributionSettings.attributionLength = .long
                    }else{
                        directionVC.autocompleteViewController.attributionSettings.attributionLength = .short
                    }
                }
                
                if mSearchPlaceOptions["minCharactersForSearch"] != nil {
                    let minCharactersForSearch = mSearchPlaceOptions["minCharactersForSearch"] as! Int
                    MinimumNumberOfCharacterToStartSearch = minCharactersForSearch
                }
                
                if mSearchPlaceOptions["userAddedLocationEnable"] != nil {
                    
                }
                
                if mSearchPlaceOptions["debounce"] != nil {
                    let debounce = mSearchPlaceOptions["debounce"] as! Int
                    directionVC.autocompleteViewController.debounceInterval = debounce
                }
                
                
                
                if mSearchPlaceOptions["isShowCurrentLocation"] != nil {
                    let isShowCurrentLocation = mSearchPlaceOptions["isShowCurrentLocation"] as! Bool
                    IsShowCurrentLocationEnable = isShowCurrentLocation
                }
                
                directionVC.autocompleteFilter = self.autoCompleteFilter(params: mSearchPlaceOptions)
                
            }
            
            
            if let appDelegate = UIApplication.shared.delegate {
                if let window = appDelegate.window {
                    if let rootVC = window?.rootViewController {
                        if let navVC = rootVC.navigationController {
                            navVC.pushViewController(directionVC, animated: false)
                        } else {
                            rootVC.present(directionVC, animated: false, completion: nil)
                            print("React: present: DirectionsViewController")
                        }
                    }
                }
            }
            
        }
        
        
    }
    
    private func toCategoryCodes(categories: [NSDictionary]) -> [MapplsNearbyCategories]{
        var categoriesList = [MapplsNearbyCategories]()
        categories.forEach { (item: NSDictionary) in
            let categoryName = item["category"] as! String
            let categoryCodes = item["categoryCode"] as! [String]
            let isSelected = item["isSelected"] as? Bool ?? false
            let icon = item["icon"] as! NSDictionary
            let iconUrl = icon["uri"] as! String
            let markerIcon = item["markerIcon"] as! NSDictionary
            let markerIconUrl = markerIcon["uri"] as! String
            DispatchQueue.global().async {
                let iconData = try? Data(contentsOf: URL(string: iconUrl)!)
                let markerData = try? Data(contentsOf: URL(string: markerIconUrl)!)
                DispatchQueue.main.async {
                    categoriesList.append(MapplsNearbyCategories(title: categoryName, selectedImage: UIImage(data: iconData!)!, isSelected: isSelected, categoryKeywords: categoryCodes, mapNearbyCategoryIcon: UIImage(data: markerData!)!))
                }
            }
            
        }
        return categoriesList
    }
    
    
    
    func didRequestForPreviewRoute(for steps: [RouteStep]?) {
        
    }
    
    
    
    func didRequestForStartNavigation(for routes: [Route], viewController: UIViewController, locations: [MapplsDirectionLocation], selectedRouteIndex: Int, error: NSError) {
        let returnDictionary = NSMutableDictionary()
        
        returnDictionary["selectedIndex"] = selectedRouteIndex
        
        let directionResponse = NSMutableDictionary()
        let routesArray = NSMutableArray()
        
        for route in routes {
            var data: [String: Any?] = [
                "distance": route.distance,
                "duration": route.expectedTravelTime,
                "geometry": route.geometry,
                "routeIndex": route.routeIndex,
            ]
            if route.legs != nil {
                var legList: [Any] = [Any]()
                for legs in route.legs {
                    var legsDict: [String: Any?] = [
                        "distance": legs.distance,
                        "duration": legs.expectedTravelTime,
                        "summary": legs.description,
                    ]
                    var stepsList: [Any] = [Any]()
                    for steps in legs.steps {
                        var stepsDict: [String: Any?] = [
                            "distance": steps.distance,
                            "duration": steps.expectedTravelTime,
                            "geometry": PolylineUtility(coordinates: route.coordinates!,precision: 1e6).encodedPolyline,
                            "name": steps.names?.count ?? 0 > 0 ? steps.names![0]: "",
                            "destinations": steps.destinations?.count ?? 0 > 0 ? steps.destinations![0]: nil,
                            "mode": steps.transportType.description,
                            "pronunciation": steps.instructions,
                            "rotary_name": steps.exitNames?.count ?? 0 > 0 ? steps.exitNames![0]: nil,
                            "rotary_pronunciation": steps.phoneticExitNames?.count ?? 0 > 0 ? steps.phoneticExitNames![0]: nil,
                            "driving_side": steps.drivingSide.description,
                            "maneuver": [
                                "degree": steps.maneuverDegree,
                                "location": [steps.maneuverLocation.longitude, steps.maneuverLocation.latitude],
                                "bearing_before": steps.initialHeading,
                                "bearing_after": steps.finalHeading,
                                "instruction": steps.instructions,
                                "type": steps.maneuverType.description,
                                "modifier": steps.maneuverDirection.description,
                                "exit": steps.exitIndex,
                                "short_instruction": steps.shortInstruction,
                                "maneuver_id": steps.maneuverId
                            ]
                        ]
                        if let bannerInstruction = steps.instructionsDisplayedAlongStep {
                            var bannerInstructionList = [Any]()
                            for displayInstruction in bannerInstruction {
                                var displaydict: [String: Any?] = [
                                    "distance_along_geometry": displayInstruction.distanceAlongStep,
                                ]
                                let primaryInstruction = displayInstruction.primaryInstruction
                                    var primaryDict: [String: Any?] = [
                                        "modifier": primaryInstruction.maneuverDirection.description,
                                        "text": primaryInstruction.text,
                                        "type": primaryInstruction.maneuverType.description,
                                        "degrees": primaryInstruction.finalHeading,
                                        "driving_side": steps.drivingSide.description
                                    ]
                                var primaryComponentList = [Any]()
                                for componentItem in primaryInstruction.components {
                                    let componentDict: [String: Any?] = [
                                        "text": primaryInstruction.text,
                                        "type": primaryInstruction.maneuverType.description,
                                    ]
                                    primaryComponentList.append(componentDict)
                                }
                                primaryDict["components"] = primaryComponentList
                                displaydict["primary"] = primaryDict
                                bannerInstructionList.append(displaydict)
                                
                            }
                            stepsDict["banner_instructions"] = bannerInstructionList
                        }
                        if let voiceInstruction = steps.instructionsSpokenAlongStep {
                            var voiceInstuctionList = [Any]()
                            for spokenInstruction in voiceInstruction {
                                let spokenDict: [String: Any?] = [
                                    "distanceAlongGeometry": spokenInstruction.distanceAlongStep,
                                    "announcement": spokenInstruction.text,
                                    "ssmlAnnouncement": spokenInstruction.ssmlText
                                ]
                                voiceInstuctionList.append(spokenDict)
                            }
                            stepsDict["voice_instructions"] = voiceInstuctionList
                        }
                        if let intersections = steps.intersections {
                            var intersectionList = [Any]()
                            for stepsintersection in intersections {
                                let intersectionDict = NSMutableDictionary()
                                intersectionDict["out"] = stepsintersection.outletIndex
                                intersectionDict["in"] = stepsintersection.approachIndex
                                let bearingsArray = NSMutableArray()
                                let entryArray = NSMutableArray()
                                for (index, bearing) in stepsintersection.headings.enumerated() {
                                    bearingsArray.add(bearing)
                                    entryArray.add(stepsintersection.outletIndexes.contains(index))
                                }
                                intersectionDict["bearings"] = bearingsArray
                                
                                intersectionDict["classes"] = stepsintersection.outletRoadClasses?.description
                                intersectionDict["location"] = [stepsintersection.location.longitude, stepsintersection.location.latitude]
                                
                                intersectionDict["entry"] = entryArray

                                if let lanes = stepsintersection.approachLanes {
                                    var lanesList = [Any]()
                                    for (index, laneItem) in lanes.enumerated() {
                                        lanesList.append([
                                            "valid": stepsintersection.usableApproachLanes?.contains(index) ?? false,
                                            "indications": [laneItem.indications.description]
                                        ])
                                    }
                                    intersectionDict["lanes"] = lanesList
                                }
                                intersectionList.append(intersectionDict)
                            }
                            stepsDict["intersections"] = intersectionList
                        }
                        
                        stepsList.append(stepsDict)
                    }
                    legsDict["steps"] = stepsList
                    legsDict["annotation"] = [
                        "distance": legs.segmentDistances,
                        "duration": legs.expectedSegmentTravelTimes,
                        "speed": legs.segmentSpeeds,
                        "congestion": legs.segmentCongestionLevels?.map { $0.description },
                        "baseDuration": legs.segmentBaseDurations?.map { $0.description },
                        "nodes": legs.segmentNodes,
                        "spdlmt": legs.segmentSpeedLimits?.map { $0.description }
                        //                        "maxspeed": legs.segmen
                    ]
                    legList.append(legsDict)
                }
                data["legs"] = legList
            }
            
            var coordinates: [String] = [String]()
            for waypoint in route.routeOptions.waypoints {
                if(waypoint.mapplsPin != nil) {
                    coordinates.append(waypoint.mapplsPin!)
                } else {
                    coordinates.append("\(waypoint.coordinate.longitude),\(waypoint.coordinate.latitude)")
                }
            }
            var routeOption: [String: Any?] = [
                //                "deviceID": item.routeOptions.
                //                "user": item.routeOptions.user
                "profile": route.routeOptions.profileIdentifier.rawValue,
                "resource": route.routeOptions.resourceIdentifier.rawValue,
                "coordinates": coordinates,
                "alternatives": route.routeOptions.includesAlternativeRoutes,
                //                "radiuses": item.routeOptions.rad
                //                "bearings": item.routeOptions.
                //                "language": item.routeOptions.lan
                //                "lessverbose": item.routeOptions.less
                "geometries": route.routeOptions.shapeFormat.description,
                "overview": route.routeOptions.routeShapeResolution.description,
                "steps": route.routeOptions.includesSteps,
                "annotations": route.routeOptions.attributeOptions.description,
                "exclude": route.routeOptions.roadClassesToAvoid.description,
            ]
            
            data["routeOptions"] = routeOption
            routesArray.add(data)
            
        }
        
        directionResponse["routes"] = routesArray
        
        let wayPoints = NSMutableArray()
        
        for location in locations {
            
            let locationDictionary = NSMutableDictionary()
            
            
            let locationString = (location.location)!.components(separatedBy: ",")
            let lat=(locationString[1] as NSString).doubleValue
            let lng=(locationString[0] as NSString).doubleValue
            locationDictionary["location"] = [lng,lat]
            
            locationDictionary["name"] = location.displayName
            
            wayPoints.add(locationDictionary)
        }
        directionResponse["waypoints"] = wayPoints
        directionResponse["code"] = "Ok"
        returnDictionary["directionsResponse"] = directionResponse
        
        
        resolver!(returnDictionary)
        UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: false, completion: nil)
    }
    
    
    func didRequestForGoBack(for view: MapplsDirectionTopBannerView) {
        rejecter!("Cancel", "Close", nil)
        UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: false, completion: nil)
    }
    
    func didRequestForAddViapoint(_ sender: UIButton, for isEditMode: Bool) {
        
    }
    
    func didRequestDirections() {
        
    }
    
    func didRequestForPreviewRoute(for routes: [Route], locations: [MapplsDirectionLocation]) {
        
    }
    
    //setting autoComplete options
    func autoCompleteFilter(params : NSDictionary) -> MapplsAutocompleteFilter {
        let autocompleteFilter = MapplsAutocompleteFilter()
        if params["tokenizeAddress"] != nil {
            let mTokenizeAddress=params["tokenizeAddress"] as! Bool
            if mTokenizeAddress {
                autocompleteFilter.attributions = mTokenizeAddress
            }
        }
        
        if params["pod"] != nil {
            print()
            let pod = params["pod"] as! String
            autocompleteFilter.resultPlaceType = MapplsPodType(pod)
        }
        
        if params["location"] != nil {
            let locationString = (params["location"] as! NSArray)
            if locationString.count==2 {
                let lat=(locationString[1] as! NSNumber).doubleValue
                let lng=(locationString[0] as! NSNumber).doubleValue
                autocompleteFilter.origin = CLLocation(latitude: lat, longitude:lng)
            }
        }
        
        if params["filter"] != nil {
            let mFilter = params["filter"] as! String
            
            if mFilter.contains("bounds") {
                let filterArray = (params["filter"] as! String).components(separatedBy: ":")
                let boundsArray = filterArray[1].components(separatedBy: ";")
                let firstBound = boundsArray[0].components(separatedBy: ",")
                let secondBound = boundsArray[1].components(separatedBy: ",")
                let firstLng=(firstBound[1] as NSString).doubleValue
                let firstLat=(firstBound[0] as NSString).doubleValue
                let secondLng=(secondBound[1] as NSString).doubleValue
                let secondLat=(secondBound[0] as NSString).doubleValue
                
                let southwest = CLLocationCoordinate2D(latitude: firstLat, longitude: firstLng)
                let northeast = CLLocationCoordinate2D(latitude: secondLat, longitude: secondLng)
                autocompleteFilter.searchAreaRestrictions = MapplsBoundsFilter(bounds: MapplsRectangularRegion(topLeft: northeast, bottomRight: southwest))
            }
            else if mFilter.contains("cop")  {
                let filterArray = (params["filter"] as! String).components(separatedBy: ":")
                
                autocompleteFilter.searchAreaRestrictions = MapplsPinFilter(pincode: filterArray[1])
            }
            
        }
        
        
        return autocompleteFilter
    }
    
    
    //add locations to direaction
    func addDirectionLocations(dictionary:NSDictionary,key:String,locationType:MapplsDirectionLocationType) -> MapplsDirectionLocation? {
        var  mDirectionLocation: MapplsDirectionLocation?
        let key = dictionary[key] as! NSDictionary
        
        
        
        if key["longitude"] != nil && key["latitude"] != nil {
            let longitude = key["longitude"] as! NSNumber
            let latitude = key["latitude"] as! NSNumber
            let name = key["name"] as! String
            let address = key["address"] as! String
            
            mDirectionLocation = MapplsDirectionLocation(location:"\(longitude),\(latitude)", displayName: name, displayAddress: address, locationType: locationType)
            
            
        } else if key["mapplsPin"] != nil {
            
            let eloc = key["mapplsPin"] as! String
            let name = key["name"] as! String
            let address = key["address"] as! String
            
            mDirectionLocation = MapplsDirectionLocation(location:eloc, displayName: name, displayAddress: address, locationType: locationType)
        }
        return mDirectionLocation
    }
    
    
    //color string from react native to ios
    func colorWithHexString(hexString: String, alpha:CGFloat = 1.0) -> UIColor {
        
        // Convert hex string to an integer
        let hexint = Int(self.intFromHexString(hexStr: hexString))
        let red = CGFloat((hexint & 0xff0000) >> 16) / 255.0
        let green = CGFloat((hexint & 0xff00) >> 8) / 255.0
        let blue = CGFloat((hexint & 0xff) >> 0) / 255.0
        
        // Create color object, specifying alpha as well
        let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
        return color
    }
    
    func intFromHexString(hexStr: String) -> UInt32 {
        var hexInt: UInt32 = 0
        // Create scanner
        let scanner: Scanner = Scanner(string: hexStr)
        // Tell scanner to skip the # character
        scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
        // Scan hex value
        scanner.scanHexInt32(&hexInt)
        return hexInt
    }
}
