binaryninja/collaboration/
sync.rs

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
use super::{
    Changeset, MergeConflict, Remote, RemoteFile, RemoteFolder, RemoteProject, RemoteSnapshot,
};
use binaryninjacore_sys::*;
use std::ffi::{c_char, c_void};
use std::mem::ManuallyDrop;
use std::ptr::NonNull;

use crate::binary_view::{BinaryView, BinaryViewExt};
use crate::database::{snapshot::Snapshot, Database};
use crate::file_metadata::FileMetadata;
use crate::progress::{NoProgressCallback, ProgressCallback};
use crate::project::file::ProjectFile;
use crate::rc::Ref;
use crate::string::{BnStrCompatible, BnString};
use crate::type_archive::{TypeArchive, TypeArchiveMergeConflict};

// TODO: PathBuf
/// Get the default directory path for a remote Project. This is based off the Setting for
/// collaboration.directory, the project's id, and the project's remote's id.
pub fn default_project_path(project: &RemoteProject) -> Result<BnString, ()> {
    let result = unsafe { BNCollaborationDefaultProjectPath(project.handle.as_ptr()) };
    let success = !result.is_null();
    success
        .then(|| unsafe { BnString::from_raw(result) })
        .ok_or(())
}

// TODO: PathBuf
// Get the default filepath for a remote File. This is based off the Setting for
// collaboration.directory, the file's id, the file's project's id, and the file's
// remote's id.
pub fn default_file_path(file: &RemoteFile) -> Result<BnString, ()> {
    let result = unsafe { BNCollaborationDefaultFilePath(file.handle.as_ptr()) };
    let success = !result.is_null();
    success
        .then(|| unsafe { BnString::from_raw(result) })
        .ok_or(())
}

// TODO: AsRef<Path>
/// Download a file from its remote, saving all snapshots to a database in the
/// specified location. Returns a FileContext for opening the file later.
///
/// * `file` - Remote File to download and open
/// * `db_path` - File path for saved database
pub fn download_file<S: BnStrCompatible>(
    file: &RemoteFile,
    db_path: S,
) -> Result<Ref<FileMetadata>, ()> {
    download_file_with_progress(file, db_path, NoProgressCallback)
}

// TODO: AsRef<Path>
/// Download a file from its remote, saving all snapshots to a database in the
/// specified location. Returns a FileContext for opening the file later.
///
/// * `file` - Remote File to download and open
/// * `db_path` - File path for saved database
/// * `progress` - Function to call for progress updates
pub fn download_file_with_progress<S: BnStrCompatible, F: ProgressCallback>(
    file: &RemoteFile,
    db_path: S,
    mut progress: F,
) -> Result<Ref<FileMetadata>, ()> {
    let db_path = db_path.into_bytes_with_nul();
    let result = unsafe {
        BNCollaborationDownloadFile(
            file.handle.as_ptr(),
            db_path.as_ref().as_ptr() as *const c_char,
            Some(F::cb_progress_callback),
            &mut progress as *mut F as *mut c_void,
        )
    };
    let success = !result.is_null();
    success
        .then(|| unsafe { Ref::new(FileMetadata::from_raw(result)) })
        .ok_or(())
}

/// Upload a file, with database, to the remote under the given project
///
/// * `project` - Remote project under which to place the new file
/// * `parent_folder` - Optional parent folder in which to place this file
/// * `metadata` - Local file with database
/// * `name_changeset` - Function to call for naming a pushed changeset, if necessary
pub fn upload_database<N: NameChangeset>(
    project: &RemoteProject,
    parent_folder: Option<&RemoteFolder>,
    metadata: &FileMetadata,
    name_changeset: N,
) -> Result<Ref<RemoteFile>, ()> {
    upload_database_with_progress(
        project,
        parent_folder,
        metadata,
        name_changeset,
        NoProgressCallback,
    )
}

/// Upload a file, with database, to the remote under the given project
///
/// * `metadata` - Local file with database
/// * `project` - Remote project under which to place the new file
/// * `parent_folder` - Optional parent folder in which to place this file
/// * `name_changeset` - Function to call for naming a pushed changeset, if necessary
/// * `progress` - Function to call for progress updates
pub fn upload_database_with_progress<P: ProgressCallback, N: NameChangeset>(
    project: &RemoteProject,
    parent_folder: Option<&RemoteFolder>,
    metadata: &FileMetadata,
    mut name_changeset: N,
    mut progress: P,
) -> Result<Ref<RemoteFile>, ()> {
    let folder_raw = parent_folder.map_or(std::ptr::null_mut(), |h| h.handle.as_ptr());
    let result = unsafe {
        BNCollaborationUploadDatabase(
            metadata.handle,
            project.handle.as_ptr(),
            folder_raw,
            Some(P::cb_progress_callback),
            &mut progress as *mut P as *mut c_void,
            Some(N::cb_name_changeset),
            &mut name_changeset as *mut N as *mut c_void,
        )
    };
    NonNull::new(result)
        .map(|raw| unsafe { RemoteFile::ref_from_raw(raw) })
        .ok_or(())
}

/// Test if a database is valid for use in collaboration
pub fn is_collaboration_database(database: &Database) -> bool {
    unsafe { BNCollaborationIsCollaborationDatabase(database.handle.as_ptr()) }
}

/// Get the Remote for a Database
pub fn get_remote_for_local_database(database: &Database) -> Result<Option<Ref<Remote>>, ()> {
    let mut value = std::ptr::null_mut();
    let success =
        unsafe { BNCollaborationGetRemoteForLocalDatabase(database.handle.as_ptr(), &mut value) };
    success
        .then(|| NonNull::new(value).map(|handle| unsafe { Remote::ref_from_raw(handle) }))
        .ok_or(())
}

/// Get the Remote for a BinaryView
pub fn get_remote_for_binary_view(bv: &BinaryView) -> Result<Option<Ref<Remote>>, ()> {
    let Some(db) = bv.file().database() else {
        return Ok(None);
    };
    get_remote_for_local_database(&db)
}

/// Get the Remote Project for a Database, returning the Remote project from one of the
/// connected remotes, or None if not found or if projects are not pulled
pub fn get_remote_project_for_local_database(
    database: &Database,
) -> Result<Option<Ref<RemoteProject>>, ()> {
    let mut value = std::ptr::null_mut();
    let success = unsafe {
        BNCollaborationGetRemoteProjectForLocalDatabase(database.handle.as_ptr(), &mut value)
    };
    success
        .then(|| NonNull::new(value).map(|handle| unsafe { RemoteProject::ref_from_raw(handle) }))
        .ok_or(())
}

/// Get the Remote File for a Database
pub fn get_remote_file_for_local_database(
    database: &Database,
) -> Result<Option<Ref<RemoteFile>>, ()> {
    let mut value = std::ptr::null_mut();
    let success = unsafe {
        BNCollaborationGetRemoteFileForLocalDatabase(database.handle.as_ptr(), &mut value)
    };
    success
        .then(|| NonNull::new(value).map(|handle| unsafe { RemoteFile::ref_from_raw(handle) }))
        .ok_or(())
}

/// Add a snapshot to the id map in a database
pub fn assign_snapshot_map(
    local_snapshot: &Snapshot,
    remote_snapshot: &RemoteSnapshot,
) -> Result<(), ()> {
    let success = unsafe {
        BNCollaborationAssignSnapshotMap(
            local_snapshot.handle.as_ptr(),
            remote_snapshot.handle.as_ptr(),
        )
    };
    success.then_some(()).ok_or(())
}

/// Get the remote snapshot associated with a local snapshot (if it exists)
pub fn get_remote_snapshot_from_local(snap: &Snapshot) -> Result<Option<Ref<RemoteSnapshot>>, ()> {
    let mut value = std::ptr::null_mut();
    let success =
        unsafe { BNCollaborationGetRemoteSnapshotFromLocal(snap.handle.as_ptr(), &mut value) };
    success
        .then(|| NonNull::new(value).map(|handle| unsafe { RemoteSnapshot::ref_from_raw(handle) }))
        .ok_or(())
}

/// Get the local snapshot associated with a remote snapshot (if it exists)
pub fn get_local_snapshot_for_remote(
    snapshot: &RemoteSnapshot,
    database: &Database,
) -> Result<Option<Ref<Snapshot>>, ()> {
    let mut value = std::ptr::null_mut();
    let success = unsafe {
        BNCollaborationGetLocalSnapshotFromRemote(
            snapshot.handle.as_ptr(),
            database.handle.as_ptr(),
            &mut value,
        )
    };
    success
        .then(|| NonNull::new(value).map(|handle| unsafe { Snapshot::ref_from_raw(handle) }))
        .ok_or(())
}

pub fn download_database<S>(file: &RemoteFile, location: S, force: bool) -> Result<(), ()>
where
    S: BnStrCompatible,
{
    download_database_with_progress(file, location, force, NoProgressCallback)
}

pub fn download_database_with_progress<S, F>(
    file: &RemoteFile,
    location: S,
    force: bool,
    mut progress: F,
) -> Result<(), ()>
where
    S: BnStrCompatible,
    F: ProgressCallback,
{
    let db_path = location.into_bytes_with_nul();
    let success = unsafe {
        BNCollaborationDownloadDatabaseForFile(
            file.handle.as_ptr(),
            db_path.as_ref().as_ptr() as *const c_char,
            force,
            Some(F::cb_progress_callback),
            &mut progress as *mut _ as *mut c_void,
        )
    };
    success.then_some(()).ok_or(())
}

/// Completely sync a database, pushing/pulling/merging/applying changes
///
/// * `database` - Database to sync
/// * `file` - File to sync with
/// * `conflict_handler` - Function to call to resolve snapshot conflicts
/// * `name_changeset` - Function to call for naming a pushed changeset, if necessary
pub fn sync_database<C: DatabaseConflictHandler, N: NameChangeset>(
    database: &Database,
    file: &RemoteFile,
    conflict_handler: C,
    name_changeset: N,
) -> Result<(), ()> {
    sync_database_with_progress(
        database,
        file,
        conflict_handler,
        name_changeset,
        NoProgressCallback,
    )
}

/// Completely sync a database, pushing/pulling/merging/applying changes
///
/// * `database` - Database to sync
/// * `file` - File to sync with
/// * `conflict_handler` - Function to call to resolve snapshot conflicts
/// * `name_changeset` - Function to call for naming a pushed changeset, if necessary
/// * `progress` - Function to call for progress updates
pub fn sync_database_with_progress<
    C: DatabaseConflictHandler,
    P: ProgressCallback,
    N: NameChangeset,
>(
    database: &Database,
    file: &RemoteFile,
    mut conflict_handler: C,
    mut name_changeset: N,
    mut progress: P,
) -> Result<(), ()> {
    let success = unsafe {
        BNCollaborationSyncDatabase(
            database.handle.as_ptr(),
            file.handle.as_ptr(),
            Some(C::cb_handle_conflict),
            &mut conflict_handler as *mut C as *mut c_void,
            Some(P::cb_progress_callback),
            &mut progress as *mut P as *mut c_void,
            Some(N::cb_name_changeset),
            &mut name_changeset as *mut N as *mut c_void,
        )
    };
    success.then_some(()).ok_or(())
}

/// Pull updated snapshots from the remote. Merge local changes with remote changes and
/// potentially create a new snapshot for unsaved changes, named via name_changeset.
///
/// * `database` - Database to pull
/// * `file` - Remote File to pull to
/// * `conflict_handler` - Function to call to resolve snapshot conflicts
/// * `name_changeset` - Function to call for naming a pushed changeset, if necessary
pub fn pull_database<C: DatabaseConflictHandler, N: NameChangeset>(
    database: &Database,
    file: &RemoteFile,
    conflict_handler: C,
    name_changeset: N,
) -> Result<usize, ()> {
    pull_database_with_progress(
        database,
        file,
        conflict_handler,
        name_changeset,
        NoProgressCallback,
    )
}

/// Pull updated snapshots from the remote. Merge local changes with remote changes and
/// potentially create a new snapshot for unsaved changes, named via name_changeset.
///
/// * `database` - Database to pull
/// * `file` - Remote File to pull to
/// * `conflict_handler` - Function to call to resolve snapshot conflicts
/// * `name_changeset` - Function to call for naming a pushed changeset, if necessary
/// * `progress` - Function to call for progress updates
pub fn pull_database_with_progress<
    C: DatabaseConflictHandler,
    P: ProgressCallback,
    N: NameChangeset,
>(
    database: &Database,
    file: &RemoteFile,
    mut conflict_handler: C,
    mut name_changeset: N,
    mut progress: P,
) -> Result<usize, ()> {
    let mut count = 0;
    let success = unsafe {
        BNCollaborationPullDatabase(
            database.handle.as_ptr(),
            file.handle.as_ptr(),
            &mut count,
            Some(C::cb_handle_conflict),
            &mut conflict_handler as *mut C as *mut c_void,
            Some(P::cb_progress_callback),
            &mut progress as *mut P as *mut c_void,
            Some(N::cb_name_changeset),
            &mut name_changeset as *mut N as *mut c_void,
        )
    };
    success.then_some(count).ok_or(())
}

/// Merge all leaf snapshots in a database down to a single leaf snapshot.
///
/// * `database` - Database to merge
/// * `conflict_handler` - Function to call for progress updates
pub fn merge_database<C: DatabaseConflictHandler>(
    database: &Database,
    conflict_handler: C,
) -> Result<(), ()> {
    merge_database_with_progress(database, conflict_handler, NoProgressCallback)
}

/// Merge all leaf snapshots in a database down to a single leaf snapshot.
///
/// * `database` - Database to merge
/// * `conflict_handler` - Function to call for progress updates
/// * `progress` - Function to call to resolve snapshot conflicts
pub fn merge_database_with_progress<C: DatabaseConflictHandler, P: ProgressCallback>(
    database: &Database,
    mut conflict_handler: C,
    mut progress: P,
) -> Result<(), ()> {
    let success = unsafe {
        BNCollaborationMergeDatabase(
            database.handle.as_ptr(),
            Some(C::cb_handle_conflict),
            &mut conflict_handler as *mut C as *mut c_void,
            Some(P::cb_progress_callback),
            &mut progress as *mut P as *mut c_void,
        )
    };
    success.then_some(()).ok_or(())
}

/// Push locally added snapshots to the remote
///
/// * `database` - Database to push
/// * `file` - Remote File to push to
pub fn push_database(database: &Database, file: &RemoteFile) -> Result<usize, ()> {
    push_database_with_progress(database, file, NoProgressCallback)
}

/// Push locally added snapshots to the remote
///
/// * `database` - Database to push
/// * `file` - Remote File to push to
/// * `progress` - Function to call for progress updates
pub fn push_database_with_progress<P: ProgressCallback>(
    database: &Database,
    file: &RemoteFile,
    mut progress: P,
) -> Result<usize, ()> {
    let mut count = 0;
    let success = unsafe {
        BNCollaborationPushDatabase(
            database.handle.as_ptr(),
            file.handle.as_ptr(),
            &mut count,
            Some(P::cb_progress_callback),
            &mut progress as *mut P as *mut c_void,
        )
    };
    success.then_some(count).ok_or(())
}

/// Print debug information about a database to stdout
pub fn dump_database(database: &Database) -> Result<(), ()> {
    let success = unsafe { BNCollaborationDumpDatabase(database.handle.as_ptr()) };
    success.then_some(()).ok_or(())
}

/// Ignore a snapshot from database syncing operations
///
/// * `database` - Parent database
/// * `snapshot` - Snapshot to ignore
pub fn ignore_snapshot(database: &Database, snapshot: &Snapshot) -> Result<(), ()> {
    let success = unsafe {
        BNCollaborationIgnoreSnapshot(database.handle.as_ptr(), snapshot.handle.as_ptr())
    };
    success.then_some(()).ok_or(())
}

/// Test if a snapshot is ignored from the database
///
/// * `database` - Parent database
/// * `snapshot` - Snapshot to test
pub fn is_snapshot_ignored(database: &Database, snapshot: &Snapshot) -> bool {
    unsafe { BNCollaborationIsSnapshotIgnored(database.handle.as_ptr(), snapshot.handle.as_ptr()) }
}

/// Get the remote author of a local snapshot
///
/// * `database` - Parent database
/// * `snapshot` - Snapshot to query
pub fn get_snapshot_author(
    database: &Database,
    snapshot: &Snapshot,
) -> Result<Option<BnString>, ()> {
    let mut value = std::ptr::null_mut();
    let success = unsafe {
        BNCollaborationGetSnapshotAuthor(
            database.handle.as_ptr(),
            snapshot.handle.as_ptr(),
            &mut value,
        )
    };
    success
        .then(|| (!value.is_null()).then(|| unsafe { BnString::from_raw(value) }))
        .ok_or(())
}

/// Set the remote author of a local snapshot (does not upload)
///
/// * `database` - Parent database
/// * `snapshot` - Snapshot to edit
/// * `author` - Target author
pub fn set_snapshot_author<S: BnStrCompatible>(
    database: &Database,
    snapshot: &Snapshot,
    author: S,
) -> Result<(), ()> {
    let author = author.into_bytes_with_nul();
    let success = unsafe {
        BNCollaborationSetSnapshotAuthor(
            database.handle.as_ptr(),
            snapshot.handle.as_ptr(),
            author.as_ref().as_ptr() as *const c_char,
        )
    };
    success.then_some(()).ok_or(())
}

// TODO: this needs to be removed imo
pub(crate) fn pull_projects(database: &Database) -> Result<bool, ()> {
    let Some(remote) = get_remote_for_local_database(database)? else {
        return Ok(false);
    };
    remote.pull_projects()?;
    Ok(true)
}

// TODO: This needs to be removed imo
pub(crate) fn pull_files(database: &Database) -> Result<bool, ()> {
    if !pull_projects(database)? {
        return Ok(false);
    }
    let Some(project) = get_remote_project_for_local_database(database)? else {
        return Ok(false);
    };
    project.pull_files()?;
    Ok(true)
}

/// Completely sync a type archive, pushing/pulling/merging/applying changes
///
/// * `type_archive` - TypeArchive to sync
/// * `file` - File to sync with
/// * `conflict_handler` - Function to call to resolve snapshot conflicts
pub fn sync_type_archive<C: TypeArchiveConflictHandler>(
    type_archive: &TypeArchive,
    file: &RemoteFile,
    conflict_handler: C,
) -> Result<(), ()> {
    sync_type_archive_with_progress(type_archive, file, conflict_handler, NoProgressCallback)
}

/// Completely sync a type archive, pushing/pulling/merging/applying changes
///
/// * `type_archive` - TypeArchive to sync
/// * `file` - File to sync with
/// * `conflict_handler` - Function to call to resolve snapshot conflicts
/// * `progress` - Function to call for progress updates
pub fn sync_type_archive_with_progress<C: TypeArchiveConflictHandler, P: ProgressCallback>(
    type_archive: &TypeArchive,
    file: &RemoteFile,
    mut conflict_handler: C,
    mut progress: P,
) -> Result<(), ()> {
    let success = unsafe {
        BNCollaborationSyncTypeArchive(
            type_archive.handle.as_ptr(),
            file.handle.as_ptr(),
            Some(C::cb_handle_conflict),
            &mut conflict_handler as *mut C as *mut c_void,
            Some(P::cb_progress_callback),
            &mut progress as *mut P as *mut c_void,
        )
    };
    success.then_some(()).ok_or(())
}

/// Push locally added snapshots to the remote
///
/// * `type_archive` - TypeArchive to push
/// * `file` - Remote File to push to
pub fn push_type_archive(type_archive: &TypeArchive, file: &RemoteFile) -> Result<usize, ()> {
    push_type_archive_with_progress(type_archive, file, NoProgressCallback)
}

/// Push locally added snapshots to the remote
///
/// * `type_archive` - TypeArchive to push
/// * `file` - Remote File to push to
/// * `progress` - Function to call for progress updates
pub fn push_type_archive_with_progress<P: ProgressCallback>(
    type_archive: &TypeArchive,
    file: &RemoteFile,
    mut progress: P,
) -> Result<usize, ()> {
    let mut count = 0;
    let success = unsafe {
        BNCollaborationPushTypeArchive(
            type_archive.handle.as_ptr(),
            file.handle.as_ptr(),
            &mut count,
            Some(P::cb_progress_callback),
            &mut progress as *mut P as *mut c_void,
        )
    };
    success.then_some(count).ok_or(())
}

/// Pull updated type archives from the remote.
///
/// * `type_archive` - TypeArchive to pull
/// * `file` - Remote File to pull to
/// * `conflict_handler` - Function to call to resolve snapshot conflicts
pub fn pull_type_archive<C: TypeArchiveConflictHandler>(
    type_archive: &TypeArchive,
    file: &RemoteFile,
    conflict_handler: C,
) -> Result<usize, ()> {
    pull_type_archive_with_progress(type_archive, file, conflict_handler, NoProgressCallback)
}

/// Pull updated type archives from the remote.
///
/// * `type_archive` - TypeArchive to pull
/// * `file` - Remote File to pull to
/// * `conflict_handler` - Function to call to resolve snapshot conflicts
/// * `progress` - Function to call for progress updates
pub fn pull_type_archive_with_progress<C: TypeArchiveConflictHandler, P: ProgressCallback>(
    type_archive: &TypeArchive,
    file: &RemoteFile,
    mut conflict_handler: C,
    mut progress: P,
) -> Result<usize, ()> {
    let mut count = 0;
    let success = unsafe {
        BNCollaborationPullTypeArchive(
            type_archive.handle.as_ptr(),
            file.handle.as_ptr(),
            &mut count,
            Some(C::cb_handle_conflict),
            &mut conflict_handler as *mut C as *mut c_void,
            Some(P::cb_progress_callback),
            &mut progress as *mut P as *mut c_void,
        )
    };
    success.then_some(count).ok_or(())
}

/// Test if a type archive is valid for use in collaboration
pub fn is_collaboration_type_archive(type_archive: &TypeArchive) -> bool {
    unsafe { BNCollaborationIsCollaborationTypeArchive(type_archive.handle.as_ptr()) }
}

/// Get the Remote for a Type Archive
pub fn get_remote_for_local_type_archive(type_archive: &TypeArchive) -> Option<Ref<Remote>> {
    let value =
        unsafe { BNCollaborationGetRemoteForLocalTypeArchive(type_archive.handle.as_ptr()) };
    NonNull::new(value).map(|handle| unsafe { Remote::ref_from_raw(handle) })
}

/// Get the Remote Project for a Type Archive
pub fn get_remote_project_for_local_type_archive(
    database: &TypeArchive,
) -> Option<Ref<RemoteProject>> {
    let value =
        unsafe { BNCollaborationGetRemoteProjectForLocalTypeArchive(database.handle.as_ptr()) };
    NonNull::new(value).map(|handle| unsafe { RemoteProject::ref_from_raw(handle) })
}

/// Get the Remote File for a Type Archive
pub fn get_remote_file_for_local_type_archive(database: &TypeArchive) -> Option<Ref<RemoteFile>> {
    let value =
        unsafe { BNCollaborationGetRemoteFileForLocalTypeArchive(database.handle.as_ptr()) };
    NonNull::new(value).map(|handle| unsafe { RemoteFile::ref_from_raw(handle) })
}

/// Get the remote snapshot associated with a local snapshot (if it exists) in a Type Archive
pub fn get_remote_snapshot_from_local_type_archive<S: BnStrCompatible>(
    type_archive: &TypeArchive,
    snapshot_id: S,
) -> Option<Ref<RemoteSnapshot>> {
    let snapshot_id = snapshot_id.into_bytes_with_nul();
    let value = unsafe {
        BNCollaborationGetRemoteSnapshotFromLocalTypeArchive(
            type_archive.handle.as_ptr(),
            snapshot_id.as_ref().as_ptr() as *const c_char,
        )
    };
    NonNull::new(value).map(|handle| unsafe { RemoteSnapshot::ref_from_raw(handle) })
}

/// Get the local snapshot associated with a remote snapshot (if it exists) in a Type Archive
pub fn get_local_snapshot_from_remote_type_archive(
    snapshot: &RemoteSnapshot,
    type_archive: &TypeArchive,
) -> Option<BnString> {
    let value = unsafe {
        BNCollaborationGetLocalSnapshotFromRemoteTypeArchive(
            snapshot.handle.as_ptr(),
            type_archive.handle.as_ptr(),
        )
    };
    (!value.is_null()).then(|| unsafe { BnString::from_raw(value) })
}

/// Test if a snapshot is ignored from the archive
pub fn is_type_archive_snapshot_ignored<S: BnStrCompatible>(
    type_archive: &TypeArchive,
    snapshot_id: S,
) -> bool {
    let snapshot_id = snapshot_id.into_bytes_with_nul();
    unsafe {
        BNCollaborationIsTypeArchiveSnapshotIgnored(
            type_archive.handle.as_ptr(),
            snapshot_id.as_ref().as_ptr() as *const c_char,
        )
    }
}

/// Download a type archive from its remote, saving all snapshots to an archive in the
/// specified `location`. Returns a [`TypeArchive`] for using later.
pub fn download_type_archive<S: BnStrCompatible>(
    file: &RemoteFile,
    location: S,
) -> Result<Option<Ref<TypeArchive>>, ()> {
    download_type_archive_with_progress(file, location, NoProgressCallback)
}

/// Download a type archive from its remote, saving all snapshots to an archive in the
/// specified `location`. Returns a [`TypeArchive`] for using later.
pub fn download_type_archive_with_progress<S: BnStrCompatible, F: ProgressCallback>(
    file: &RemoteFile,
    location: S,
    mut progress: F,
) -> Result<Option<Ref<TypeArchive>>, ()> {
    let mut value = std::ptr::null_mut();
    let db_path = location.into_bytes_with_nul();
    let success = unsafe {
        BNCollaborationDownloadTypeArchive(
            file.handle.as_ptr(),
            db_path.as_ref().as_ptr() as *const c_char,
            Some(F::cb_progress_callback),
            &mut progress as *mut F as *mut c_void,
            &mut value,
        )
    };
    success
        .then(|| NonNull::new(value).map(|handle| unsafe { TypeArchive::ref_from_raw(handle) }))
        .ok_or(())
}

/// Upload a type archive
pub fn upload_type_archive(
    archive: &TypeArchive,
    project: &RemoteProject,
    // TODO: Is this required?
    folder: &RemoteFolder,
    core_file: &ProjectFile,
) -> Result<Ref<RemoteFile>, ()> {
    upload_type_archive_with_progress(archive, project, folder, core_file, NoProgressCallback)
}

/// Upload a type archive
pub fn upload_type_archive_with_progress<P: ProgressCallback>(
    archive: &TypeArchive,
    project: &RemoteProject,
    // TODO: Is this required?
    folder: &RemoteFolder,
    // TODO: I dislike the word "core" just say local?
    core_file: &ProjectFile,
    mut progress: P,
) -> Result<Ref<RemoteFile>, ()> {
    let mut value = std::ptr::null_mut();
    let success = unsafe {
        BNCollaborationUploadTypeArchive(
            archive.handle.as_ptr(),
            project.handle.as_ptr(),
            folder.handle.as_ptr(),
            Some(P::cb_progress_callback),
            &mut progress as *const P as *mut c_void,
            core_file.handle.as_ptr(),
            &mut value,
        )
    };
    success
        .then(|| {
            NonNull::new(value)
                .map(|handle| unsafe { RemoteFile::ref_from_raw(handle) })
                .unwrap()
        })
        .ok_or(())
}

/// Merge a pair of snapshots and create a new snapshot with the result.
pub fn merge_snapshots<C: DatabaseConflictHandler>(
    first: &Snapshot,
    second: &Snapshot,
    conflict_handler: C,
) -> Result<Snapshot, ()> {
    merge_snapshots_with_progress(first, second, conflict_handler, NoProgressCallback)
}

/// Merge a pair of snapshots and create a new snapshot with the result.
pub fn merge_snapshots_with_progress<C: DatabaseConflictHandler, P: ProgressCallback>(
    first: &Snapshot,
    second: &Snapshot,
    mut conflict_handler: C,
    mut progress: P,
) -> Result<Snapshot, ()> {
    let value = unsafe {
        BNCollaborationMergeSnapshots(
            first.handle.as_ptr(),
            second.handle.as_ptr(),
            Some(C::cb_handle_conflict),
            &mut conflict_handler as *mut C as *mut c_void,
            Some(P::cb_progress_callback),
            &mut progress as *mut P as *mut c_void,
        )
    };
    NonNull::new(value)
        .map(|handle| unsafe { Snapshot::from_raw(handle) })
        .ok_or(())
}

pub trait NameChangeset: Sized {
    fn name_changeset(&mut self, changeset: &Changeset) -> bool;

    unsafe extern "C" fn cb_name_changeset(
        ctxt: *mut ::std::os::raw::c_void,
        changeset: *mut BNCollaborationChangeset,
    ) -> bool {
        let ctxt: &mut Self = &mut *(ctxt as *mut Self);
        let raw_changeset_ptr = NonNull::new(changeset).unwrap();
        // TODO: Do we take ownership with a ref here or not?
        let changeset = Changeset::from_raw(raw_changeset_ptr);
        ctxt.name_changeset(&changeset)
    }
}

impl<F> NameChangeset for F
where
    F: for<'a> FnMut(&'a Changeset) -> bool,
{
    fn name_changeset(&mut self, changeset: &Changeset) -> bool {
        self(changeset)
    }
}

pub struct NoNameChangeset;

impl NameChangeset for NoNameChangeset {
    fn name_changeset(&mut self, _changeset: &Changeset) -> bool {
        unreachable!()
    }

    unsafe extern "C" fn cb_name_changeset(
        _ctxt: *mut std::os::raw::c_void,
        _changeset: *mut BNCollaborationChangeset,
    ) -> bool {
        true
    }
}

/// Helper trait that resolves conflicts
pub trait DatabaseConflictHandler: Sized {
    /// Handle any merge conflicts by calling their success() function with a merged value
    ///
    /// * `conflicts` - conflicts ids to conflicts structures
    ///
    /// Return true if all conflicts were successfully merged
    fn handle_conflict(&mut self, keys: &str, conflicts: &MergeConflict) -> bool;

    unsafe extern "C" fn cb_handle_conflict(
        ctxt: *mut c_void,
        keys: *mut *const c_char,
        conflicts: *mut *mut BNAnalysisMergeConflict,
        conflict_count: usize,
    ) -> bool {
        let ctxt: &mut Self = &mut *(ctxt as *mut Self);
        let keys = core::slice::from_raw_parts(keys, conflict_count);
        let conflicts = core::slice::from_raw_parts(conflicts, conflict_count);
        keys.iter().zip(conflicts.iter()).all(|(key, conflict)| {
            // NOTE this is a reference, not owned, so ManuallyDrop is required, or just implement `ref_from_raw`
            // TODO: Replace with raw_to_string
            let key = ManuallyDrop::new(BnString::from_raw(*key as *mut _));
            // TODO I guess dont drop here?
            let raw_ptr = NonNull::new(*conflict).unwrap();
            let conflict = MergeConflict::from_raw(raw_ptr);
            ctxt.handle_conflict(key.as_str(), &conflict)
        })
    }
}

impl<F> DatabaseConflictHandler for F
where
    F: for<'a> FnMut(&'a str, &'a MergeConflict) -> bool,
{
    fn handle_conflict(&mut self, keys: &str, conflicts: &MergeConflict) -> bool {
        self(keys, conflicts)
    }
}

pub struct DatabaseConflictHandlerFail;
impl DatabaseConflictHandler for DatabaseConflictHandlerFail {
    fn handle_conflict(&mut self, _keys: &str, _conflicts: &MergeConflict) -> bool {
        unreachable!()
    }

    unsafe extern "C" fn cb_handle_conflict(
        _ctxt: *mut c_void,
        _keys: *mut *const c_char,
        _conflicts: *mut *mut BNAnalysisMergeConflict,
        conflict_count: usize,
    ) -> bool {
        // Fail if we have any conflicts.
        conflict_count > 0
    }
}

pub trait TypeArchiveConflictHandler: Sized {
    fn handle_conflict(&mut self, conflicts: &TypeArchiveMergeConflict) -> bool;
    unsafe extern "C" fn cb_handle_conflict(
        ctxt: *mut ::std::os::raw::c_void,
        conflicts: *mut *mut BNTypeArchiveMergeConflict,
        conflict_count: usize,
    ) -> bool {
        let ctx: &mut Self = &mut *(ctxt as *mut Self);
        // TODO: Verify that we dont own the merge conflict, or this list passed to us.
        let conflicts_raw = core::slice::from_raw_parts(conflicts, conflict_count);
        conflicts_raw
            .iter()
            .map(|t| NonNull::new_unchecked(*t))
            .map(|t| TypeArchiveMergeConflict::from_raw(t))
            .all(|conflict| ctx.handle_conflict(&conflict))
    }
}

impl<F> TypeArchiveConflictHandler for F
where
    F: for<'a> FnMut(&'a TypeArchiveMergeConflict) -> bool,
{
    fn handle_conflict(&mut self, conflicts: &TypeArchiveMergeConflict) -> bool {
        self(conflicts)
    }
}

pub struct TypeArchiveConflictHandlerFail;
impl TypeArchiveConflictHandler for TypeArchiveConflictHandlerFail {
    fn handle_conflict(&mut self, _conflicts: &TypeArchiveMergeConflict) -> bool {
        unreachable!()
    }

    unsafe extern "C" fn cb_handle_conflict(
        _ctxt: *mut c_void,
        _conflicts: *mut *mut BNTypeArchiveMergeConflict,
        _conflict_count: usize,
    ) -> bool {
        // TODO only fail if _conflict_count is greater then 0?
        //_conflict_count > 0
        false
    }
}