File size: 13,741 Bytes
fefce67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
350debe
 
90a13c0
fefce67
350debe
90a13c0
 
 
350debe
90a13c0
 
 
 
 
350debe
 
fefce67
 
1baca0b
fefce67
 
350debe
90a13c0
fefce67
350debe
 
90a13c0
fefce67
90a13c0
350debe
90a13c0
 
 
 
 
fefce67
350debe
 
 
fefce67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
350debe
fefce67
 
 
350debe
90a13c0
350debe
fefce67
350debe
fefce67
350debe
 
 
 
90a13c0
 
 
350debe
 
 
90a13c0
350debe
 
 
 
90a13c0
 
 
 
 
 
 
 
 
a3ca6ea
90a13c0
350debe
90a13c0
 
 
 
 
350debe
90a13c0
 
 
 
 
 
 
 
 
 
 
 
 
350debe
 
90a13c0
 
350debe
90a13c0
 
 
350debe
 
fefce67
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
// import { Request, Response } from 'express';
// import { TrackModel } from '../models/TrackModel';
// import { TrackFeature, TrackFeatureCollection } from '../types/types';

// /**
//  * TrackController - Handles HTTP requests for public ski tracks
//  */
// export class TrackController {
//     private static parseOptionalString(value: unknown): string | undefined {
//         if (typeof value !== 'string') return undefined;
//         const trimmed = value.trim();
//         if (!trimmed || trimmed === 'undefined' || trimmed === 'null') return undefined;
//         return trimmed;
//     }

//     private static normalizeStringList(values: unknown[]): string[] | undefined {
//         const normalized = values
//             .filter((v): v is string => typeof v === 'string')
//             .map(v => v.trim().toLowerCase())
//             .filter(v => v.length > 0 && v !== 'undefined' && v !== 'null');

//         if (normalized.length === 0) return undefined;
//         return Array.from(new Set(normalized));
//     }

//     private static parseActivitiesParam(value: unknown): string[] | undefined {
//         if (Array.isArray(value)) {
//             return TrackController.normalizeStringList(value);
//         }

//         if (typeof value === 'string') {
//             return TrackController.normalizeStringList(value.split(','));
//         }

//         return undefined;
//     }

//     /**
//      * GET /api/tracks
//      * Fetch all public tracks with optional location filtering and pagination
//      */
//     static async getTracks(req: Request, res: Response): Promise<void> {
//         console.log('--- Start getTracks Controller ---');
//         try {
//             const { lat, lng, radius, q, activities, difficulty } = req.query;
//             console.log(`Received query parameters: lat=${lat}, lng=${lng}, radius=${radius}, q=${q}, activities=${activities}, difficulty=${difficulty}`);

//             // Prepare filters for DB query
//             const filters: { activities?: string[], searchQuery?: string, difficulty?: string } = {};
            
//             const parsedActivities = TrackController.parseActivitiesParam(activities);
//             if (parsedActivities) {
//                 filters.activities = parsedActivities;
//             }

//             const parsedQuery = TrackController.parseOptionalString(q);
//             if (parsedQuery) {
//                 filters.searchQuery = parsedQuery;
//             }

//             const parsedDifficulty = TrackController.parseOptionalString(difficulty);
//             if (parsedDifficulty) {
//                 filters.difficulty = parsedDifficulty;
//             }

//             // Pagination (must be applied at DB level to avoid huge Supabase egress)
//             const page = Math.max(1, parseInt(req.query.page as string) || 1);
//             const requestedLimit = parseInt(req.query.limit as string) || 100;
//             const limit = Math.min(Math.max(1, requestedLimit), 200);
//             const offset = (page - 1) * limit;

//             const locationFilter = (lat && lng && radius)
//                 ? {
//                     lat: parseFloat(lat as string),
//                     lng: parseFloat(lng as string),
//                     radiusKm: parseFloat(radius as string),
//                 }
//                 : undefined;

//             // Fetch filtered + paginated tracks from DB
//             const { tracks, total } = await TrackModel.findWithFiltersPaginated(
//                 filters,
//                 { limit, offset },
//                 locationFilter
//             );
//             console.log(`Fetched ${tracks.length} tracks from the database (after DB filtering + pagination). Total matching: ${total}.`);

//             // Convert tracks to GeoJSON features
//             const features: TrackFeature[] = tracks.map(track => {
//                 return {
//                     type: 'Feature',
//                     geometry: typeof track.geojson === 'string'
//                         ? JSON.parse(track.geojson as any)
//                         : track.geojson,
//                     properties: {
//                         id: track.id,
//                         external_id: track.external_id,
//                         name: track.name,
//                         description: track.description,
//                         ...track.properties,
//                         difficulty: track.difficulty,
//                         difficulty_convention: track.difficulty_convention,
//                         type: track.type,
//                         uses: track.uses,
//                         ref: track.ref,
//                         oneway: track.oneway,
//                         gladed: track.gladed,
//                         patrolled: track.patrolled,
//                         lit: track.lit,
//                         grooming: track.grooming,
//                         status: track.status,
//                         websites: track.websites,
//                         wikidata_id: track.wikidata_id,
//                         elevation_profile: track.elevation_profile
//                     }
//                 };
//             });

//             const totalPages = Math.ceil(total / limit);
//             console.log(`Response features count: ${features.length}. Total pages: ${totalPages}.`);

//             const response: TrackFeatureCollection & { pagination: any } = {
//                 type: 'FeatureCollection',
//                 features,
//                 pagination: {
//                     total,
//                     page,
//                     limit,
//                     pages: totalPages
//                 }
//             };

//             res.json(response);
//             console.log('--- End getTracks Controller (Success) ---');
//         } catch (err) {
//             console.error('Error in getTracks:', err);
//             res.status(500).json({ error: 'Server Error' });
//             console.log('--- End getTracks Controller (Error) ---');
//         }
//     }

//     /**
//      * GET /api/tracks/:id
//      * Fetch a single track by ID
//      */
//     static async getTrackById(req: Request, res: Response): Promise<void> {
//         console.log('--- Start getTrackById Controller ---');
//         try {
//             const id = parseInt(req.params.id);
//             console.log(`Fetching track with ID: ${id}`);

//             const track = await TrackModel.findById(id);

//             if (!track) {
//                 console.log(`Track with ID ${id} not found.`);
//                 res.status(404).json({ error: 'Track not found' });
//                 return;
//             }

//             const feature: TrackFeature = {
//                 type: 'Feature',
//                 geometry: typeof track.geojson === 'string'
//                     ? JSON.parse(track.geojson)
//                     : track.geojson,
//                 properties: {
//                     id: track.id,
//                     name: track.name,
//                     description: track.description,
//                     ...track.properties,
//                     difficulty: track.difficulty,
//                     type: track.type
//                 }
//             };

//             res.json(feature);
//             console.log('--- End getTrackById Controller (Success) ---');
//         } catch (err) {
//             console.error('Error in getTrackById:', err);
//             res.status(500).json({ error: 'Server Error' });
//             console.log('--- End getTrackById Controller (Error) ---');
//         }
//     }
// }



import { Request, Response } from 'express';
import { TrackModel } from '../models/TrackModel';
import { TrackFeature, TrackFeatureCollection } from '../types/types';
import { getDistanceFromLatLonInKm } from '../utils/geoUtils';

/**
 * TrackController - Handles HTTP requests for public ski tracks
 */
export class TrackController {
    /**
     * GET /api/tracks
     * Fetch all public tracks with optional location filtering and pagination
     */
    static async getTracks(req: Request, res: Response): Promise<void> {
        console.log('--- Start getTracks Controller ---');
        try {
            const { lat, lng, radius } = req.query;
            console.log(`Received query parameters: lat=${lat}, lng=${lng}, radius=${radius}`);

            const tracks = await TrackModel.findAll();
            console.log(`Fetched ${tracks.length} tracks from the database.`);

            // Convert tracks to GeoJSON features
            let features: TrackFeature[] = tracks.map(track => {
                return {
                    type: 'Feature',
                    geometry: typeof track.geojson === 'string'
                        ? JSON.parse(track.geojson)
                        : track.geojson,
                    properties: {
                        id: track.id,
                        name: track.name,
                        description: track.description,
                        ...track.properties,
                        difficulty: track.difficulty,
                        type: track.type
                    }
                };
            });
            console.log(`Initial features count after mapping: ${features.length}`);

            // Filter by location if provided
            if (lat && lng && radius) {
                console.log('Location filtering is active.');
                const centerLat = parseFloat(lat as string);
                const centerLng = parseFloat(lng as string);
                const radiusKm = parseFloat(radius as string);
                console.log(`Filter criteria: Center Lat=${centerLat}, Lng=${centerLng}, Radius=${radiusKm} km.`);

                const initialFeatureCount = features.length;
                features = features.filter(feature => {
                    if (!feature.geometry || !feature.geometry.coordinates || feature.geometry.coordinates.length === 0) {
                        return false;
                    }

                    // Use the first point of the track for distance check
                    // GeoJSON coordinates are [lng, lat]
                    const trackPoint = feature.geometry.coordinates[0];
                    const trackLng = trackPoint[0];
                    const trackLat = trackPoint[1];

                    const dist = getDistanceFromLatLonInKm(centerLat, centerLng, trackLat, trackLng);
                    return dist <= radiusKm;
                });
                console.log(`Features remaining after location filter: ${features.length}. Filtered out ${initialFeatureCount - features.length} features.`);
            } else {
                console.log('No location filter applied.');
            }

            // Pagination
            const page = parseInt(req.query.page as string) || 1;
            const limit = parseInt(req.query.limit as string) || 100;
            const startIndex = (page - 1) * limit;
            const endIndex = page * limit;
            console.log(`Pagination parameters: Page=${page}, Limit=${limit}. Total features: ${features.length}`);
            console.log(`Slicing features from index ${startIndex} to ${endIndex}.`);

            const paginatedFeatures = features.slice(startIndex, endIndex);
            const totalPages = Math.ceil(features.length / limit);
            console.log(`Response features count: ${paginatedFeatures.length}. Total pages: ${totalPages}.`);

            const response: TrackFeatureCollection & { pagination: any } = {
                type: 'FeatureCollection',
                features: paginatedFeatures,
                pagination: {
                    total: features.length,
                    page,
                    limit,
                    pages: totalPages
                }
            };

            res.json(response);
            console.log('--- End getTracks Controller (Success) ---');
        } catch (err) {
            console.error('Error in getTracks:', err);
            res.status(500).json({ error: 'Server Error' });
            console.log('--- End getTracks Controller (Error) ---');
        }
    }

    /**
     * GET /api/tracks/:id
     * Fetch a single track by ID
     */
    static async getTrackById(req: Request, res: Response): Promise<void> {
        console.log('--- Start getTrackById Controller ---');
        try {
            const id = parseInt(req.params.id);
            console.log(`Fetching track with ID: ${id}`);

            const track = await TrackModel.findById(id);

            if (!track) {
                console.log(`Track with ID ${id} not found.`);
                res.status(404).json({ error: 'Track not found' });
                return;
            }

            const feature: TrackFeature = {
                type: 'Feature',
                geometry: typeof track.geojson === 'string'
                    ? JSON.parse(track.geojson)
                    : track.geojson,
                properties: {
                    id: track.id,
                    name: track.name,
                    description: track.description,
                    ...track.properties,
                    difficulty: track.difficulty,
                    type: track.type
                }
            };

            res.json(feature);
            console.log('--- End getTrackById Controller (Success) ---');
        } catch (err) {
            console.error('Error in getTrackById:', err);
            res.status(500).json({ error: 'Server Error' });
            console.log('--- End getTrackById Controller (Error) ---');
        }
    }
}