import { Site } from '../../../regions/business/models/site';
import { LocationVC } from '../../presentation/validationClasses/locationValidationClass';
import { TimeTrackingEntryPrototype } from '../models/timeTrackingEntry';
import { cosineDistanceBetweenPoints } from './distance';

export const isLocationWithinTolerance = (location: LocationVC, site: Site) => {
    const siteLocation = site.getLocation();
    if (siteLocation.tolerance === 0) {
        return true;
    }
    const distance = cosineDistanceBetweenPoints(location.latitude, location.longitude, siteLocation.latitude, siteLocation.longitude);
    return distance <= siteLocation.tolerance;
};

export const hasLocationIncidence = (entry: TimeTrackingEntryPrototype, siteOrMap: Site | Map<number, Site>): boolean => {
    if (!entry.siteId || entry.kioskId || entry.isRemoteWork) {
        return false;
    }
    const site = siteOrMap instanceof Map ? siteOrMap.get(entry.siteId) : siteOrMap;
    if (!site) {
        return false;
    }
    return !entry.location || !isLocationWithinTolerance(entry.location, site);
};

export const getSiteCellValue = (entry: TimeTrackingEntryPrototype | undefined, sites: Map<number, Site>, remoteWorkLabel: string): string | null => {
    if (!entry) return null;
    if (entry.siteId && sites.has(entry.siteId)) return sites.get(entry.siteId)!.getName();
    if (entry.isRemoteWork) return remoteWorkLabel;
    return null;
};
