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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
//! This module contains the C foreign function interface for cavalier_contours.
#![allow(non_camel_case_types)]
use cavalier_contours::{
    core::math::Vector2,
    polyline::{
        BooleanOp, PlineBooleanOptions, PlineOffsetOptions, PlineSource, PlineSourceMut,
        PlineVertex, Polyline,
    },
    static_aabb2d_index::StaticAABB2DIndex,
};
use core::slice;
use std::{convert::TryFrom, panic};

/// Helper macro to catch unwind and return -1 if panic was caught otherwise returns whatever the
/// expression returned.
macro_rules! ffi_catch_unwind {
    ($body: expr) => {
        match panic::catch_unwind(move || $body) {
            Ok(r) => r,
            Err(_) => -1,
        }
    };
}

/// Opaque type that wraps a [StaticAABB2DIndex].
///
/// Note the internal member is only public for composing in other Rust libraries wanting to use the
/// FFI opaque type as part of their FFI API.
#[derive(Debug, Clone)]
pub struct cavc_aabbindex(pub StaticAABB2DIndex<f64>);

/// Represents a simple 2D point with x and y coordinate values.
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct cavc_point {
    pub x: f64,
    pub y: f64,
}

impl cavc_point {
    pub fn new(x: f64, y: f64) -> Self {
        cavc_point { x, y }
    }

    pub fn from_internal(v: Vector2<f64>) -> Self {
        cavc_point::new(v.x, v.y)
    }
}

/// Represents a polyline vertex holding x, y, and bulge.
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct cavc_vertex {
    pub x: f64,
    pub y: f64,
    pub bulge: f64,
}

impl cavc_vertex {
    pub fn new(x: f64, y: f64, bulge: f64) -> Self {
        cavc_vertex { x, y, bulge }
    }

    pub fn from_internal(v: PlineVertex<f64>) -> Self {
        cavc_vertex::new(v.x, v.y, v.bulge)
    }
}

/// Opaque type that wraps a [Polyline].
///
/// Note the internal member is only public for composing in other Rust libraries wanting to use the
/// FFI opaque type as part of their FFI API.
#[derive(Debug, Clone)]
pub struct cavc_pline(pub Polyline<f64>);

/// FFI representation of [PlineOffsetOptions].
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct cavc_pline_parallel_offset_o {
    pub aabb_index: *const cavc_aabbindex,
    pub pos_equal_eps: f64,
    pub slice_join_eps: f64,
    pub offset_dist_eps: f64,
    pub handle_self_intersects: u8,
}

impl cavc_pline_parallel_offset_o {
    /// Convert FFI parallel offset options type to internal type.
    ///
    /// # Safety
    ///
    /// `aabb_index` field must be null or a valid pointer to a [cavc_aabbindex].
    pub unsafe fn to_internal(&self) -> PlineOffsetOptions<f64> {
        PlineOffsetOptions {
            aabb_index: self.aabb_index.as_ref().map(|w| &w.0),
            pos_equal_eps: self.pos_equal_eps,
            slice_join_eps: self.slice_join_eps,
            offset_dist_eps: self.offset_dist_eps,
            handle_self_intersects: self.handle_self_intersects != 0,
        }
    }
}

impl Default for cavc_pline_parallel_offset_o {
    fn default() -> Self {
        let d = PlineOffsetOptions::default();
        Self {
            aabb_index: std::ptr::null(),
            pos_equal_eps: d.pos_equal_eps,
            slice_join_eps: d.slice_join_eps,
            offset_dist_eps: d.offset_dist_eps,
            handle_self_intersects: d.handle_self_intersects as u8,
        }
    }
}

/// Write default option values to a [cavc_pline_parallel_offset_o].
///
/// ## Specific Error Codes
/// * 1 = `options` is null.
///
/// # Safety
///
/// `options` must point to a valid place in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_parallel_offset_o_init(
    options: *mut cavc_pline_parallel_offset_o,
) -> i32 {
    ffi_catch_unwind!({
        if options.is_null() {
            return 1;
        }

        options.write(Default::default());
        0
    })
}

/// FFI representation of [PlineBooleanOptions].
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct cavc_pline_boolean_o {
    pub pline1_aabb_index: *const cavc_aabbindex,
    pub pos_equal_eps: f64,
}

impl cavc_pline_boolean_o {
    /// Convert FFI boolean options type to internal type.
    ///
    /// # Safety
    ///
    /// `pline1_aabb_index` field must be null or a valid pointer to a [cavc_aabbindex].
    pub unsafe fn to_internal(&self) -> PlineBooleanOptions<f64> {
        PlineBooleanOptions {
            pline1_aabb_index: self.pline1_aabb_index.as_ref().map(|w| &w.0),
            pos_equal_eps: self.pos_equal_eps,
        }
    }
}

impl Default for cavc_pline_boolean_o {
    fn default() -> Self {
        let d = PlineBooleanOptions::default();
        Self {
            pline1_aabb_index: std::ptr::null(),
            pos_equal_eps: d.pos_equal_eps,
        }
    }
}

/// Write default option values to a [cavc_pline_boolean_o].
///
/// ## Specific Error Codes
/// * 1 = `options` is null.
///
/// # Safety
///
/// `options` must point to a valid place in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_boolean_o_init(options: *mut cavc_pline_boolean_o) -> i32 {
    ffi_catch_unwind!({
        if options.is_null() {
            return 1;
        }

        options.write(Default::default());
        0
    })
}

fn boolean_op_from_u32(i: u32) -> Option<BooleanOp> {
    if i == 0 {
        Some(BooleanOp::Or)
    } else if i == 1 {
        Some(BooleanOp::And)
    } else if i == 2 {
        Some(BooleanOp::Not)
    } else if i == 3 {
        Some(BooleanOp::Xor)
    } else {
        None
    }
}

/// Opaque type that represents a list of [cavc_pline].
///
/// Note the internal member is only public for composing in other Rust libraries wanting to use the
/// FFI opaque type as part of their FFI API.
pub struct cavc_plinelist(pub Vec<*mut cavc_pline>);

impl cavc_plinelist {
    pub fn from_internal<I>(plines: I) -> *mut cavc_plinelist
    where
        I: IntoIterator<Item = Polyline>,
    {
        let r = plines
            .into_iter()
            .map(|pl| Box::into_raw(Box::new(cavc_pline(pl))))
            .collect();

        Box::into_raw(Box::new(cavc_plinelist(r)))
    }
}

/// Create a new polyline object.
///
/// `vertexes` is an array of [cavc_vertex] to create the polyline with (may be null if `n_vertexes`
/// is 0).
/// `n_vertexes` contains the number of vertexes in the array.
/// `is_closed` sets the polyline to be closed if non-zero.
/// `pline` is an out parameter to hold the created polyline.
///
/// # Safety
///
/// `vertexes` may be null if `n_vertexes` is 0 or must point to a valid contiguous buffer of
/// [cavc_vertex] with length of at least `n_vertexes`.
/// `pline` must point to a valid place in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_create(
    vertexes: *const cavc_vertex,
    n_vertexes: u32,
    is_closed: u8,
    pline: *mut *const cavc_pline,
) -> i32 {
    ffi_catch_unwind!({
        let mut result = Polyline::new();
        if is_closed != 0 {
            result.set_is_closed(true);
        }

        if !vertexes.is_null() && n_vertexes != 0 {
            let data = slice::from_raw_parts(vertexes, n_vertexes as usize);
            result.reserve(data.len());
            for v in data {
                result.add(v.x, v.y, v.bulge);
            }
        }

        pline.write(Box::into_raw(Box::new(cavc_pline(result))));
        0
    })
}

/// Free an existing [cavc_pline] object.
///
/// Nothing happens if `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not already been freed.
#[no_mangle]
pub unsafe extern "C" fn cavc_pline_f(pline: *mut cavc_pline) {
    if !pline.is_null() {
        drop(Box::from_raw(pline))
    }
}

/// Reserve space for an `additional` number of vertexes in the [cavc_pline].
///
/// This function is used to avoid allocations when adding vertexes to the [cavc_pline].
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_reserve(pline: *mut cavc_pline, additional: u32) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }

        (*pline).0.reserve(additional as usize);
        0
    })
}

/// Clones the polyline.
///
/// `pline` is the polyline to be cloned.
/// `cloned` is used as an out parameter to hold the new polyline from cloning.
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
/// `cloned` must point to a valid place in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_clone(
    pline: *const cavc_pline,
    cloned: *mut *const cavc_pline,
) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }

        cloned.write(Box::into_raw(Box::new(cavc_pline((*pline).0.clone()))));
        0
    })
}

/// Get whether the polyline is closed or not.
///
/// `is_closed` is used as an out parameter to hold the whether `pline` is closed (non-zero) or not
/// (zero).
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
/// `is_closed` must point to a valid place in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_get_is_closed(
    pline: *const cavc_pline,
    is_closed: *mut u8,
) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }
        is_closed.write((*pline).0.is_closed() as u8);
        0
    })
}

/// Set whether the polyline is closed or not.
///
/// If `is_closed` is non-zero then `pline` is set to be closed, otherwise it is set to be open.
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_set_is_closed(pline: *mut cavc_pline, is_closed: u8) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }
        (*pline).0.set_is_closed(is_closed != 0);
        0
    })
}

/// Get the vertex count of a polyline.
///
/// `count` used as out parameter to hold the vertex count.
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
/// `count` must point to a valid place in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_get_vertex_count(
    pline: *const cavc_pline,
    count: *mut u32,
) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }

        // using try_from to catch odd case of polyline vertex count greater than u32::MAX to
        // prevent memory corruption/access errors but just panic as internal error if it does occur
        count.write(u32::try_from((*pline).0.vertex_count()).unwrap());
        0
    })
}

/// Fills the buffer given with the vertex data of a polyline.
///
/// You must use [cavc_pline_get_vertex_count] to ensure the buffer given has adequate length
/// to be filled with all vertexes!
///
/// `vertex_data` must point to a buffer that can be filled with all `pline` vertexes.
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
/// `vertex_data` must point to a buffer that is large enough to hold all the vertexes or a buffer
/// overrun will happen.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_get_vertex_data(
    pline: *const cavc_pline,
    vertex_data: *mut cavc_vertex,
) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }

        let buffer = slice::from_raw_parts_mut(vertex_data, (*pline).0.vertex_count());
        for (i, v) in (*pline).0.iter_vertexes().enumerate() {
            buffer[i] = cavc_vertex::from_internal(v);
        }
        0
    })
}

/// Sets all of the vertexes of a polyline.
///
/// `vertex_data` is an array of vertexes to use for the polyline.
/// `n_vertexes` must specify the number of vertexes to be read from the
/// `vertex_data` array.
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
/// `vertex_data` must be a valid pointer to a buffer of at least `n_vertexes` of [cavc_vertex].
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_set_vertex_data(
    pline: *mut cavc_pline,
    vertex_data: *const cavc_vertex,
    n_vertexes: u32,
) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }

        (*pline).0.clear();
        let buffer = slice::from_raw_parts(vertex_data, n_vertexes as usize);
        (*pline).0.reserve(buffer.len());
        for v in buffer {
            (*pline).0.add(v.x, v.y, v.bulge);
        }
        0
    })
}

/// Clears all of the vertexes of a polyline.
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_clear(pline: *mut cavc_pline) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }

        (*pline).0.clear();
        0
    })
}

/// Add a vertex to a polyline `pline` with `x`, `y`, and `bulge`.
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_add(pline: *mut cavc_pline, x: f64, y: f64, bulge: f64) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }

        (*pline).0.add(x, y, bulge);
        0
    })
}

/// Get a polyline vertex at a given index position.
///
/// `position` is is the index to get the vertex at.
/// `vertex` used as out parameter to hold the vertex retrieved.
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
/// * 2 = `position` is out of bounds for the `pline` given.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
/// `vertex` must point to a valid place in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_get_vertex(
    pline: *const cavc_pline,
    position: u32,
    vertex: *mut cavc_vertex,
) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }

        if position >= (*pline).0.vertex_count() as u32 {
            return 2;
        }

        let v = (*pline).0[position as usize];
        vertex.write(cavc_vertex::from_internal(v));
        0
    })
}

/// Set a polyline vertex at a given index position.
///
/// `position` is is the index to set the vertex at.
/// `vertex` is the data to be set.
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
/// * 2 = `position` is out of bounds for the `pline` given.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_set_vertex(
    pline: *mut cavc_pline,
    position: u32,
    vertex: cavc_vertex,
) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }

        if position >= (*pline).0.vertex_count() as u32 {
            return 2;
        }

        (*pline).0[position as usize] = PlineVertex::new(vertex.x, vertex.y, vertex.bulge);
        0
    })
}

/// Remove a vertex from a polyline at an index position.
///
/// `position` is the index of the vertex to be removed from the polyline.
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
/// * 2 = `position` is out of bounds for the `pline` given.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_remove(pline: *mut cavc_pline, position: u32) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }

        if position as usize >= (*pline).0.vertex_count() {
            return 2;
        }

        (*pline).0.remove(position as usize);
        0
    })
}

/// Wraps [PlineSource::path_length].
///
/// `path_length` is used as the out parameter to hold the computed path length.
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
/// `path_length` must point to a valid place in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_eval_path_length(
    pline: *const cavc_pline,
    path_length: *mut f64,
) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }
        path_length.write((*pline).0.path_length());
        0
    })
}

/// Wraps [PlineSource::area].
///
/// `area` is used as the out parameter to hold the computed area.
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
/// `area` must point to a valid place in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_eval_area(pline: *const cavc_pline, area: *mut f64) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }
        area.write((*pline).0.area());
        0
    })
}

/// Wraps [PlineSource::winding_number].
///
/// `winding_number` is used as the out parameter to hold the computed winding number.
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
/// `winding_number` must point to a valid place in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_eval_wn(
    pline: *const cavc_pline,
    x: f64,
    y: f64,
    winding_number: *mut i32,
) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }
        winding_number.write((*pline).0.winding_number(Vector2::new(x, y)));
        0
    })
}

/// Wraps [PlineSourceMut::invert_direction_mut].
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_invert_direction(pline: *mut cavc_pline) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }
        (*pline).0.invert_direction_mut();
        0
    })
}

/// Wraps [PlineSourceMut::scale_mut].
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_scale(pline: *mut cavc_pline, scale_factor: f64) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }
        (*pline).0.scale_mut(scale_factor);
        0
    })
}

/// Wraps [PlineSourceMut::translate_mut].
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_translate(
    pline: *mut cavc_pline,
    x_offset: f64,
    y_offset: f64,
) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }
        (*pline).0.translate_mut(x_offset, y_offset);
        0
    })
}

/// Wraps [PlineSource::remove_repeat_pos] but modifies in place rather than returning a result.
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_remove_repeat_pos(
    pline: *mut cavc_pline,
    pos_equal_eps: f64,
) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }
        match (*pline).0.remove_repeat_pos(pos_equal_eps) {
            None => {
                // do nothing (no repeat positions, leave unchanged)
                0
            }
            Some(x) => {
                // update self with result
                (*pline).0 = x;
                0
            }
        }
    })
}

/// Wraps [PlineSource::remove_redundant] but modifies in place rather than returning a result.
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_remove_redundant(
    pline: *mut cavc_pline,
    pos_equal_eps: f64,
) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }
        match (*pline).0.remove_redundant(pos_equal_eps) {
            None => {
                // do nothing (no repeat positions, leave unchanged)
                0
            }
            Some(x) => {
                // update self with result
                (*pline).0 = x;
                0
            }
        }
    })
}

/// Wraps [PlineSource::extents].
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
/// * 2 = `pline` vertex count is less than 2.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
/// `min_x`, `min_y`, `max_x`, and `max_y` must all point to a valid places in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_eval_extents(
    pline: *const cavc_pline,
    min_x: *mut f64,
    min_y: *mut f64,
    max_x: *mut f64,
    max_y: *mut f64,
) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }
        match (*pline).0.extents() {
            Some(aabb) => {
                min_x.write(aabb.min_x);
                min_y.write(aabb.min_y);
                max_x.write(aabb.max_x);
                max_y.write(aabb.max_y);
                0
            }
            None => 2,
        }
    })
}

/// Wraps [PlineSource::parallel_offset_opt].
///
/// `options` is allowed to be null (default options will be used).
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
/// `result` must point to a valid place in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_parallel_offset(
    pline: *const cavc_pline,
    offset: f64,
    options: *const cavc_pline_parallel_offset_o,
    result: *mut *const cavc_plinelist,
) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }

        let results = if options.is_null() {
            (*pline).0.parallel_offset(offset)
        } else {
            (*pline)
                .0
                .parallel_offset_opt(offset, &(*options).to_internal())
        };

        result.write(cavc_plinelist::from_internal(results));
        0
    })
}
/// Wraps [PlineSource::boolean_opt].
///
/// `options` is allowed to be null (default options will be used).
///
/// Boolean operations are:
/// * 0 = [BooleanOp::Or]
/// * 1 = [BooleanOp::And]
/// * 2 = [BooleanOp::Not]
/// * 3 = [BooleanOp::Xor]
///
/// ## Specific Error Codes
/// * 1 = `pline1` and/or `pline2` is null.
/// * 2 = `operation` is unrecognized (must be one of the values listed).
///
/// # Safety
///
/// `pline1` and `pline2` must each be null or a valid cavc_pline object that was created with
/// [cavc_pline_create] and has not been freed.
/// `pos_plines` and `neg_plines` must both point to different valid places in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_boolean(
    pline1: *const cavc_pline,
    pline2: *const cavc_pline,
    operation: u32,
    options: *const cavc_pline_boolean_o,
    pos_plines: *mut *const cavc_plinelist,
    neg_plines: *mut *const cavc_plinelist,
) -> i32 {
    ffi_catch_unwind!({
        if pline1.is_null() || pline2.is_null() {
            return 1;
        }

        let op = {
            match boolean_op_from_u32(operation) {
                Some(op) => op,
                None => {
                    return 2;
                }
            }
        };
        let results = if options.is_null() {
            (*pline1).0.boolean(&(*pline2).0, op)
        } else {
            (*pline1)
                .0
                .boolean_opt(&(*pline2).0, op, &(*options).to_internal())
        };

        pos_plines.write(cavc_plinelist::from_internal(
            results.pos_plines.into_iter().map(|p| p.pline),
        ));
        neg_plines.write(cavc_plinelist::from_internal(
            results.neg_plines.into_iter().map(|p| p.pline),
        ));
        0
    })
}

/// Wraps [PlineSource::create_approx_aabb_index].
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
/// `aabbindex` must point to a valid place in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_create_approx_aabbindex(
    pline: *const cavc_pline,
    aabbindex: *mut *const cavc_aabbindex,
) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }

        let result = (*pline).0.create_approx_aabb_index();
        aabbindex.write(Box::into_raw(Box::new(cavc_aabbindex(result))));
        0
    })
}

/// Wraps [PlineSource::create_aabb_index].
///
/// ## Specific Error Codes
/// * 1 = `pline` is null.
///
/// # Safety
///
/// `pline` must be null or a valid cavc_pline object that was created with [cavc_pline_create] and
/// has not been freed.
/// `aabbindex` must point to a valid place in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_pline_create_aabbindex(
    pline: *const cavc_pline,
    aabbindex: *mut *const cavc_aabbindex,
) -> i32 {
    ffi_catch_unwind!({
        if pline.is_null() {
            return 1;
        }

        let result = (*pline).0.create_aabb_index();
        aabbindex.write(Box::into_raw(Box::new(cavc_aabbindex(result))));
        0
    })
}

/// Free an existing [cavc_aabbindex] object.
///
/// Nothing happens if `aabbindex` is null.
///
/// # Safety
///
/// `aabbindex` must be null or a valid [cavc_aabbindex] object.
#[no_mangle]
pub unsafe extern "C" fn cavc_aabbindex_f(aabbindex: *mut cavc_aabbindex) {
    if !aabbindex.is_null() {
        drop(Box::from_raw(aabbindex))
    }
}

/// Wraps the [`StaticAABB2DIndex::bounds`] method (gets total extents of the aabb index). Writes
/// NaNs if the index is empty.
///
/// ## Specific Error Codes
/// * 1 = `aabbindex` is null.
///
/// # Safety
///
/// `aabbindex` must be null or a valid [cavc_aabbindex] object.
/// `min_x`, `min_y`, `max_x`, and `max_y` must all point to a valid places in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_aabbindex_get_extents(
    aabbindex: *const cavc_aabbindex,
    min_x: *mut f64,
    min_y: *mut f64,
    max_x: *mut f64,
    max_y: *mut f64,
) -> i32 {
    ffi_catch_unwind!({
        if aabbindex.is_null() {
            return 1;
        }

        if let Some(bounds) = (*aabbindex).0.bounds() {
            min_x.write(bounds.min_x);
            min_y.write(bounds.min_y);
            max_x.write(bounds.max_x);
            max_y.write(bounds.max_y);
        } else {
            min_x.write(f64::NAN);
            min_y.write(f64::NAN);
            max_x.write(f64::NAN);
            max_y.write(f64::NAN);
        }
        0
    })
}

/// Free an existing [cavc_plinelist] object and all [cavc_pline] owned by it.
///
/// Nothing happens if `plinelist` is null.
///
/// # Safety
///
/// `plinelist` must be null or a valid [cavc_plinelist] object.
#[no_mangle]
pub unsafe extern "C" fn cavc_plinelist_f(plinelist: *mut cavc_plinelist) {
    if !plinelist.is_null() {
        drop(Box::from_raw(plinelist))
    }
}

/// Get the number of polylines inside a [cavc_plinelist].
///
/// `count` used as out parameter to hold the polyline count.
///
/// ## Specific Error Codes
/// * 1 = `plinelist` is null.
///
/// # Safety
///
/// `plinelist` must be null or a valid [cavc_plinelist] object.
/// `count` must point to a valid place in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_plinelist_get_count(
    plinelist: *const cavc_plinelist,
    count: *mut u32,
) -> i32 {
    ffi_catch_unwind!({
        if plinelist.is_null() {
            return 1;
        }

        // using try_from to catch odd case of polyline count greater than u32::MAX to
        // prevent memory corruption/access errors but just panic as internal error if it does occur
        count.write(u32::try_from((*plinelist).0.len()).unwrap());
        0
    })
}

/// Get a polyline at the given index position in the [cavc_plinelist].
///
/// `pline` used as out parameter to hold the polyline pointer. NOTE: This does not release
/// ownership of the [cavc_pline] from the [cavc_plinelist], to do that use [cavc_plinelist_pop] or
/// [cavc_plinelist_take].
///
/// ## Specific Error Codes
/// * 1 = `plinelist` is null.
/// * 2 = `position` out of range for the [cavc_plinelist].
///
/// # Safety
///
/// `plinelist` must be null or a valid [cavc_plinelist] object.
/// `pline` must point to a valid place in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_plinelist_get_pline(
    plinelist: *const cavc_plinelist,
    position: u32,
    pline: *mut *const cavc_pline,
) -> i32 {
    ffi_catch_unwind!({
        if plinelist.is_null() {
            return 1;
        }

        let pos = position as usize;

        match (*plinelist).0.get(pos) {
            Some(pl) => {
                pline.write(*pl);
                0
            }
            None => 2,
        }
    })
}

/// Efficiently release and return the last [cavc_pline] from a [cavc_plinelist].
///
/// `pline` used as out parameter to hold the polyline pointer released from the [cavc_plinelist].
/// NOTE: The caller now must call [cavc_pline_f] at some point to free the released [cavc_pline].
///
/// ## Specific Error Codes
/// * 1 = `plinelist` is null.
/// * 2 = `plinelist` is empty.
///
/// # Safety
///
/// `plinelist` must be null or a valid [cavc_plinelist] object.
/// `pline` must point to a valid place in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_plinelist_pop(
    plinelist: *mut cavc_plinelist,
    pline: *mut *const cavc_pline,
) -> i32 {
    ffi_catch_unwind!({
        if plinelist.is_null() {
            return 1;
        }

        match (*plinelist).0.pop() {
            Some(p) => {
                pline.write(p);
                0
            }
            None => 2,
        }
    })
}

/// Release and return a [cavc_pline] from a [cavc_plinelist] at a given index position.
///
/// `pline` used as out parameter to hold the polyline pointer released from the [cavc_plinelist].
/// NOTE: The caller now must call [cavc_pline_f] at some point to free the released [cavc_pline].
///
/// ## Specific Error Codes
/// * 1 = `plinelist` is null.
/// * 2 = `position` out of range for the [cavc_plinelist].
///
/// # Safety
///
/// `plinelist` must be null or a valid [cavc_plinelist] object.
/// `pline` must point to a valid place in memory to be written.
#[no_mangle]
#[must_use]
pub unsafe extern "C" fn cavc_plinelist_take(
    plinelist: *mut cavc_plinelist,
    position: u32,
    pline: *mut *const cavc_pline,
) -> i32 {
    ffi_catch_unwind!({
        if plinelist.is_null() {
            return 1;
        }

        let pos = position as usize;

        if pos >= (*plinelist).0.len() {
            return 2;
        }

        pline.write((*plinelist).0.remove(pos));
        0
    })
}