// Location Injection Script for Unite WebView
// This script injects location data when popup blocking is enabled

(function() {
    'use strict';
    
    console.log('Unite LocationInjection script loaded');
    
    // Check if geolocation is already available
    if (!navigator.geolocation) {
        console.log('Navigator.geolocation not available');
        return;
    }
    
    // Store original geolocation methods
    const originalGetCurrentPosition = navigator.geolocation.getCurrentPosition;
    const originalWatchPosition = navigator.geolocation.watchPosition;
    const originalClearWatch = navigator.geolocation.clearWatch;
    
    console.log('Overriding geolocation methods');
    
    // Override getCurrentPosition
    navigator.geolocation.getCurrentPosition = function(successCallback, errorCallback, options) {
        console.log('getCurrentPosition called with options:', options);
        
        // Send message to native code to get current location
        if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.location) {
            console.log('Sending location request to native code');
            window.webkit.messageHandlers.location.postMessage({
                type: 'getCurrentPosition',
                options: options || {}
            });
            
            // Store callbacks for when native code responds
            window._uniteLocationCallbacks = window._uniteLocationCallbacks || {};
            window._uniteLocationCallbacks.success = successCallback;
            window._uniteLocationCallbacks.error = errorCallback;
        } else {
            console.log('Native message handler not available, using fallback');
            // Fallback to original implementation
            originalGetCurrentPosition.call(this, successCallback, errorCallback, options);
        }
    };
    
    // Override watchPosition  
    navigator.geolocation.watchPosition = function(successCallback, errorCallback, options) {
        console.log('watchPosition called with options:', options);
        // Generate a fake watch ID
        const watchId = Math.floor(Math.random() * 1000000);
        
        // Call getCurrentPosition and return the watch ID
        navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
        return watchId;
    };
    
    // Override clearWatch
    navigator.geolocation.clearWatch = function(watchId) {
        console.log('clearWatch called with ID:', watchId);
        // No-op since we're not actually watching
    };
    
    // Function to be called by native code when location is available
    window.uniteInjectLocation = function(latitude, longitude, accuracy, timestamp) {
        console.log('Location injected:', latitude, longitude, accuracy, timestamp);
        
        if (window._uniteLocationCallbacks && window._uniteLocationCallbacks.success) {
            const position = {
                coords: {
                    latitude: latitude,
                    longitude: longitude,
                    accuracy: accuracy || 10,
                    altitude: null,
                    altitudeAccuracy: null,
                    heading: null,
                    speed: null
                },
                timestamp: timestamp || Date.now()
            };
            
            console.log('Calling success callback with position:', position);
            window._uniteLocationCallbacks.success(position);
            
            // Clear callbacks after use
            delete window._uniteLocationCallbacks;
        } else {
            console.log('No success callback available');
        }
    };
    
    // Function to be called by native code when location error occurs
    window.uniteInjectLocationError = function(code, message) {
        console.log('Location error injected:', code, message);
        
        if (window._uniteLocationCallbacks && window._uniteLocationCallbacks.error) {
            const error = {
                code: code || 1, // PERMISSION_DENIED = 1, POSITION_UNAVAILABLE = 2, TIMEOUT = 3
                message: message || 'Location access denied'
            };
            
            console.log('Calling error callback with error:', error);
            window._uniteLocationCallbacks.error(error);
            
            // Clear callbacks after use
            delete window._uniteLocationCallbacks;
        } else {
            console.log('No error callback available');
        }
    };
    
    // Test function to verify injection is working
    window.uniteTestLocation = function() {
        console.log('Testing location injection...');
        navigator.geolocation.getCurrentPosition(
            function(position) {
                console.log('Test success:', position);
            },
            function(error) {
                console.log('Test error:', error);
            }
        );
    };
    
})();