aboutsummaryrefslogtreecommitdiffstats
path: root/calendar/pcs/cal-backend-file.c
blob: e5e3abb7c98fde1450ef4170f3a058ed7b18726c (plain) (blame)
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
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
/* Evolution calendar - iCalendar file backend
 *
 * Copyright (C) 2000-2003 Ximian, Inc.
 *
 * Authors: Federico Mena-Quintero <federico@ximian.com>
 *          Rodrigo Moya <rodrigo@ximian.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of version 2 of the GNU General Public
 * License as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 */

#include <config.h>
#include <string.h>
#include <unistd.h>
#include <bonobo/bonobo-exception.h>
#include <bonobo/bonobo-moniker-util.h>
#include <libgnome/gnome-i18n.h>
#include <libgnomevfs/gnome-vfs.h>
#include "e-util/e-xml-hash-utils.h"
#include "cal-util/cal-recur.h"
#include "cal-util/cal-util.h"
#include "cal-backend-file-events.h"
#include "cal-backend-util.h"
#include "cal-backend-object-sexp.h"



/* Placeholder for each component and its recurrences */
typedef struct {
    CalComponent *full_object;
    GHashTable *recurrences;
} CalBackendFileObject;

/* Private part of the CalBackendFile structure */
struct _CalBackendFilePrivate {
    /* URI where the calendar data is stored */
    char *uri;

    /* Filename in the dir */
    char *file_name;    

    /* Toplevel VCALENDAR component */
    icalcomponent *icalcomp;

    /* All the objects in the calendar, hashed by UID.  The
     * hash key *is* the uid returned by cal_component_get_uid(); it is not
     * copied, so don't free it when you remove an object from the hash
     * table. Each item in the hash table is a CalBackendFileObject.
     */
    GHashTable *comp_uid_hash;

    GList *comp;
    
    /* Config database handle for free/busy organizer information */
    EConfigListener *config_listener;
    
    /* Idle handler for saving the calendar when it is dirty */
    guint idle_id;

    /* The calendar's default timezone, used for resolving DATE and
       floating DATE-TIME values. */
    icaltimezone *default_zone;

    /* The list of live queries */
    GList *queries;
};



static void cal_backend_file_dispose (GObject *object);
static void cal_backend_file_finalize (GObject *object);

static CalBackendSyncClass *parent_class;



/* g_hash_table_foreach() callback to destroy a CalComponent */
static void
free_object (gpointer key, gpointer value, gpointer data)
{
    CalBackendFileObject *obj_data = value;

    g_object_unref (obj_data->full_object);
    g_hash_table_foreach (obj_data->recurrences, (GHFunc) g_object_unref, NULL);
    g_hash_table_destroy (obj_data->recurrences);
}

/* Saves the calendar data */
static void
save (CalBackendFile *cbfile)
{
    CalBackendFilePrivate *priv;
    GnomeVFSURI *uri, *backup_uri;
    GnomeVFSHandle *handle = NULL;
    GnomeVFSResult result = GNOME_VFS_ERROR_BAD_FILE;
    GnomeVFSFileSize out;
    gchar *tmp, *backup_uristr;
    char *buf;
    
    priv = cbfile->priv;
    g_assert (priv->uri != NULL);
    g_assert (priv->icalcomp != NULL);

    uri = gnome_vfs_uri_new (priv->uri);
    if (!uri)
        goto error_malformed_uri;

    /* save calendar to backup file */
    tmp = gnome_vfs_uri_to_string (uri, GNOME_VFS_URI_HIDE_NONE);
    if (!tmp) {
        gnome_vfs_uri_unref (uri);
        goto error_malformed_uri;
    }
        
    backup_uristr = g_strconcat (tmp, "~", NULL);
    backup_uri = gnome_vfs_uri_new (backup_uristr);

    g_free (tmp);
    g_free (backup_uristr);

    if (!backup_uri) {
        gnome_vfs_uri_unref (uri);
        goto error_malformed_uri;
    }
    
    result = gnome_vfs_create_uri (&handle, backup_uri,
                                       GNOME_VFS_OPEN_WRITE,
                                       FALSE, 0666);
    if (result != GNOME_VFS_OK) {
        gnome_vfs_uri_unref (uri);
        gnome_vfs_uri_unref (backup_uri);
        goto error;
    }

    buf = icalcomponent_as_ical_string (priv->icalcomp);
    result = gnome_vfs_write (handle, buf, strlen (buf) * sizeof (char), &out);
    gnome_vfs_close (handle);
    if (result != GNOME_VFS_OK) {
        gnome_vfs_uri_unref (uri);
        gnome_vfs_uri_unref (backup_uri);
        goto error;
    }

    /* now copy the temporary file to the real file */
    result = gnome_vfs_move_uri (backup_uri, uri, TRUE);

    gnome_vfs_uri_unref (uri);
    gnome_vfs_uri_unref (backup_uri);
    if (result != GNOME_VFS_OK)
        goto error;

    return;

 error_malformed_uri:
    cal_backend_notify_error (CAL_BACKEND (cbfile),
                  _("Can't save calendar data: Malformed URI."));
    return;

 error:
    cal_backend_notify_error (CAL_BACKEND (cbfile), gnome_vfs_result_to_string (result));
    return;
}

/* Dispose handler for the file backend */
static void
cal_backend_file_dispose (GObject *object)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;

    cbfile = CAL_BACKEND_FILE (object);
    priv = cbfile->priv;

    /* Save if necessary */

    if (priv->idle_id != 0) {
        save (cbfile);
        g_source_remove (priv->idle_id);
        priv->idle_id = 0;
    }

    if (priv->comp_uid_hash) {
        g_hash_table_foreach (priv->comp_uid_hash, (GHFunc) free_object, NULL);
        g_hash_table_destroy (priv->comp_uid_hash);
        priv->comp_uid_hash = NULL;
    }

    g_list_free (priv->comp);
    priv->comp = NULL;

    if (priv->icalcomp) {
        icalcomponent_free (priv->icalcomp);
        priv->icalcomp = NULL;
    }

    if (priv->config_listener) {
        g_object_unref (priv->config_listener);
        priv->config_listener = NULL;
    }

    if (G_OBJECT_CLASS (parent_class)->dispose)
        (* G_OBJECT_CLASS (parent_class)->dispose) (object);
}

/* Finalize handler for the file backend */
static void
cal_backend_file_finalize (GObject *object)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;

    g_return_if_fail (object != NULL);
    g_return_if_fail (IS_CAL_BACKEND_FILE (object));

    cbfile = CAL_BACKEND_FILE (object);
    priv = cbfile->priv;

    /* Clean up */

    if (priv->uri) {
            g_free (priv->uri);
        priv->uri = NULL;
    }

    g_free (priv);
    cbfile->priv = NULL;

    if (G_OBJECT_CLASS (parent_class)->finalize)
        (* G_OBJECT_CLASS (parent_class)->finalize) (object);
}



/* Looks up a component by its UID on the backend's component hash table */
static CalComponent *
lookup_component (CalBackendFile *cbfile, const char *uid)
{
    CalBackendFilePrivate *priv;
    CalBackendFileObject *obj_data;

    priv = cbfile->priv;

    /* FIXME: search recurrences also */
    obj_data = g_hash_table_lookup (priv->comp_uid_hash, uid);
    return obj_data ? obj_data->full_object : NULL;
}



/* Calendar backend methods */

/* Is_read_only handler for the file backend */
static CalBackendSyncStatus
cal_backend_file_is_read_only (CalBackendSync *backend, Cal *cal, gboolean *read_only)
{
    /* we just return FALSE, since all calendars are read-write */
    *read_only = FALSE;
    
    return GNOME_Evolution_Calendar_Success;
}

/* Get_email_address handler for the file backend */
static CalBackendSyncStatus
cal_backend_file_get_cal_address (CalBackendSync *backend, Cal *cal, char **address)
{
    /* A file backend has no particular email address associated
     * with it (although that would be a useful feature some day).
     */
    *address = NULL;

    return GNOME_Evolution_Calendar_Success;
}

static CalBackendSyncStatus
cal_backend_file_get_ldap_attribute (CalBackendSync *backend, Cal *cal, char **attribute)
{
    *attribute = NULL;
    
    return GNOME_Evolution_Calendar_Success;
}

static CalBackendSyncStatus
cal_backend_file_get_alarm_email_address (CalBackendSync *backend, Cal *cal, char **address)
{
    /* A file backend has no particular email address associated
     * with it (although that would be a useful feature some day).
     */
    *address = NULL;
    
    return GNOME_Evolution_Calendar_Success;
}

static CalBackendSyncStatus
cal_backend_file_get_static_capabilities (CalBackendSync *backend, Cal *cal, char **capabilities)
{
    *capabilities = CAL_STATIC_CAPABILITY_NO_EMAIL_ALARMS;
    
    return GNOME_Evolution_Calendar_Success;
}

/* function to resolve timezones */
static icaltimezone *
resolve_tzid (const char *tzid, gpointer user_data)
{
    icalcomponent *vcalendar_comp = user_data;

        if (!tzid || !tzid[0])
                return NULL;
        else if (!strcmp (tzid, "UTC"))
                return icaltimezone_get_utc_timezone ();

    return icalcomponent_get_timezone (vcalendar_comp, tzid);
}

/* Idle handler; we save the calendar since it is dirty */
static gboolean
save_idle (gpointer data)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;

    cbfile = CAL_BACKEND_FILE (data);
    priv = cbfile->priv;

    g_assert (priv->icalcomp != NULL);

    save (cbfile);

    priv->idle_id = 0;
    return FALSE;
}

/* Marks the file backend as dirty and queues a save operation */
static void
mark_dirty (CalBackendFile *cbfile)
{
    CalBackendFilePrivate *priv;

    priv = cbfile->priv;

    if (priv->idle_id != 0)
        return;

    priv->idle_id = g_idle_add (save_idle, cbfile);
}

/* Checks if the specified component has a duplicated UID and if so changes it */
static void
check_dup_uid (CalBackendFile *cbfile, CalComponent *comp)
{
    CalBackendFilePrivate *priv;
    CalBackendFileObject *obj_data;
    const char *uid;
    char *new_uid;

    priv = cbfile->priv;

    cal_component_get_uid (comp, &uid);

    obj_data = g_hash_table_lookup (priv->comp_uid_hash, uid);
    if (!obj_data)
        return; /* Everything is fine */

    g_message ("check_dup_uid(): Got object with duplicated UID `%s', changing it...", uid);

    new_uid = cal_component_gen_uid ();
    cal_component_set_uid (comp, new_uid);
    g_free (new_uid);

    /* FIXME: I think we need to reset the SEQUENCE property and reset the
     * CREATED/DTSTAMP/LAST-MODIFIED.
     */

    mark_dirty (cbfile);
}

static char *
get_rid_string (CalComponent *comp)
{
        CalComponentRange range;
        struct icaltimetype tt;
                                                                                   
        cal_component_get_recurid (comp, &range);
        if (!range.datetime.value)
                return "0";
        tt = *range.datetime.value;
        cal_component_free_range (&range);
                                                                                   
        return icaltime_is_valid_time (tt) && !icaltime_is_null_time (tt) ?
                icaltime_as_ical_string (tt) : "0";
}

/* Tries to add an icalcomponent to the file backend.  We only store the objects
 * of the types we support; all others just remain in the toplevel component so
 * that we don't lose them.
 */
static void
add_component (CalBackendFile *cbfile, CalComponent *comp, gboolean add_to_toplevel)
{
    CalBackendFilePrivate *priv;
    CalBackendFileObject *obj_data;
    const char *uid;
    GSList *categories;

    priv = cbfile->priv;

    /* FIXME: check if it's an instance */

    /* Ensure that the UID is unique; some broken implementations spit
     * components with duplicated UIDs.
     */
    check_dup_uid (cbfile, comp);
    cal_component_get_uid (comp, &uid);

    obj_data = g_new0 (CalBackendFileObject, 1);
    obj_data->full_object = comp;
    obj_data->recurrences = g_hash_table_new (g_str_hash, g_str_equal);

    g_hash_table_insert (priv->comp_uid_hash, (gpointer) uid, obj_data);

    priv->comp = g_list_prepend (priv->comp, comp);

    /* Put the object in the toplevel component if required */

    if (add_to_toplevel) {
        icalcomponent *icalcomp;

        icalcomp = cal_component_get_icalcomponent (comp);
        g_assert (icalcomp != NULL);

        icalcomponent_add_component (priv->icalcomp, icalcomp);
    }

    /* Update the set of categories */
    cal_component_get_categories_list (comp, &categories);
    cal_backend_ref_categories (CAL_BACKEND (cbfile), categories);
    cal_component_free_categories_list (categories);
}

/* Removes a component from the backend's hash and lists.  Does not perform
 * notification on the clients.  Also removes the component from the toplevel
 * icalcomponent.
 */
static void
remove_component (CalBackendFile *cbfile, CalComponent *comp)
{
    CalBackendFilePrivate *priv;
    icalcomponent *icalcomp;
    const char *uid;
    GList *l;
    GSList *categories;
    CalBackendFileObject *obj_data;

    priv = cbfile->priv;

    /* Remove the icalcomp from the toplevel */

    icalcomp = cal_component_get_icalcomponent (comp);
    g_assert (icalcomp != NULL);

    icalcomponent_remove_component (priv->icalcomp, icalcomp);

    /* Remove it from our mapping */

    cal_component_get_uid (comp, &uid);
    obj_data = g_hash_table_lookup (priv->comp_uid_hash, uid);
    if (!obj_data)
        return;

    g_hash_table_remove (priv->comp_uid_hash, uid);

    l = g_list_find (priv->comp, comp);
    g_assert (l != NULL);
    priv->comp = g_list_delete_link (priv->comp, l);

    /* Update the set of categories */
    cal_component_get_categories_list (comp, &categories);
    cal_backend_unref_categories (CAL_BACKEND (cbfile), categories);
    cal_component_free_categories_list (categories);

    free_object (uid, obj_data, NULL);
}

/* Scans the toplevel VCALENDAR component and stores the objects it finds */
static void
scan_vcalendar (CalBackendFile *cbfile)
{
    CalBackendFilePrivate *priv;
    icalcompiter iter;

    priv = cbfile->priv;
    g_assert (priv->icalcomp != NULL);
    g_assert (priv->comp_uid_hash != NULL);

    for (iter = icalcomponent_begin_component (priv->icalcomp, ICAL_ANY_COMPONENT);
         icalcompiter_deref (&iter) != NULL;
         icalcompiter_next (&iter)) {
        icalcomponent *icalcomp;
        icalcomponent_kind kind;
        CalComponent *comp;

        icalcomp = icalcompiter_deref (&iter);
        
        kind = icalcomponent_isa (icalcomp);

        if (!(kind == ICAL_VEVENT_COMPONENT
              || kind == ICAL_VTODO_COMPONENT
              || kind == ICAL_VJOURNAL_COMPONENT))
            continue;

        comp = cal_component_new ();

        if (!cal_component_set_icalcomponent (comp, icalcomp))
            continue;

        add_component (cbfile, comp, FALSE);
    }
}

/* Parses an open iCalendar file and loads it into the backend */
static CalBackendSyncStatus
open_cal (CalBackendFile *cbfile, const char *uristr)
{
    CalBackendFilePrivate *priv;
    icalcomponent *icalcomp;

    priv = cbfile->priv;

    icalcomp = cal_util_parse_ics_file (uristr);
    if (!icalcomp)
        return GNOME_Evolution_Calendar_OtherError;

    /* FIXME: should we try to demangle XROOT components and
     * individual components as well?
     */

    if (icalcomponent_isa (icalcomp) != ICAL_VCALENDAR_COMPONENT) {
        icalcomponent_free (icalcomp);

        return GNOME_Evolution_Calendar_OtherError;
    }

    priv->icalcomp = icalcomp;

    priv->comp_uid_hash = g_hash_table_new (g_str_hash, g_str_equal);
    scan_vcalendar (cbfile);

    priv->uri = g_strdup (uristr);

    return GNOME_Evolution_Calendar_Success;
}

static CalBackendSyncStatus
create_cal (CalBackendFile *cbfile, const char *uristr)
{
    CalBackendFilePrivate *priv;

    priv = cbfile->priv;

    /* Create the new calendar information */
    priv->icalcomp = cal_util_new_top_level ();

    /* Create our internal data */
    priv->comp_uid_hash = g_hash_table_new (g_str_hash, g_str_equal);

    priv->uri = g_strdup (uristr);

    mark_dirty (cbfile);

    return GNOME_Evolution_Calendar_Success;
}

static char *
get_uri_string (CalBackend *backend)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;
    const char *master_uri;
    char *full_uri, *str_uri;
    GnomeVFSURI *uri;

    cbfile = CAL_BACKEND_FILE (backend);
    priv = cbfile->priv;
    
    master_uri = cal_backend_get_uri (backend);
    g_message (G_STRLOC ": Trying to open %s", master_uri);
    
    /* FIXME Check the error conditions a little more elegantly here */
    if (g_strrstr ("tasks.ics", master_uri) || g_strrstr ("calendar.ics", master_uri)) {
        g_warning (G_STRLOC ": Existing file name %s", master_uri);

        return NULL;
    }
    
    full_uri = g_strdup_printf ("%s%s%s", master_uri, G_DIR_SEPARATOR_S, priv->file_name);
    uri = gnome_vfs_uri_new (full_uri);
    g_free (full_uri);
    
    if (!uri)
        return NULL;

    str_uri = gnome_vfs_uri_to_string (uri,
                       (GNOME_VFS_URI_HIDE_USER_NAME
                        | GNOME_VFS_URI_HIDE_PASSWORD
                        | GNOME_VFS_URI_HIDE_HOST_NAME
                        | GNOME_VFS_URI_HIDE_HOST_PORT
                        | GNOME_VFS_URI_HIDE_TOPLEVEL_METHOD));
    gnome_vfs_uri_unref (uri);

    if (!str_uri || !strlen (str_uri)) {
        g_free (str_uri);

        return NULL;
    }   

    return str_uri;
}

/* Open handler for the file backend */
static CalBackendSyncStatus
cal_backend_file_open (CalBackendSync *backend, Cal *cal, gboolean only_if_exists)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;
    char *str_uri;
    CalBackendSyncStatus status;
    
    cbfile = CAL_BACKEND_FILE (backend);
    priv = cbfile->priv;

    /* Claim a succesful open if we are already open */
    if (priv->uri && priv->comp_uid_hash)
        return GNOME_Evolution_Calendar_Success;
    
    str_uri = get_uri_string (CAL_BACKEND (backend));
    if (!str_uri)
        return GNOME_Evolution_Calendar_OtherError;
    
    if (access (str_uri, R_OK) == 0)
        status = open_cal (cbfile, str_uri);
    else {
        if (only_if_exists)
            status = GNOME_Evolution_Calendar_NoSuchCal;
        else
            status = create_cal (cbfile, str_uri);
    }

    g_free (str_uri);

    return status;
}

static CalBackendSyncStatus
cal_backend_file_remove (CalBackendSync *backend, Cal *cal)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;
    char *str_uri;
    
    cbfile = CAL_BACKEND_FILE (backend);
    priv = cbfile->priv;

    str_uri = get_uri_string (CAL_BACKEND (backend));
    if (!str_uri)
        return GNOME_Evolution_Calendar_OtherError;

    if (access (str_uri, W_OK) != 0) {
        g_free (str_uri);

        return GNOME_Evolution_Calendar_PermissionDenied;
    }

    /* FIXME Remove backup file and whole directory too? */
    if (unlink (str_uri) != 0) {
        g_free (str_uri);

        return GNOME_Evolution_Calendar_OtherError;
    }
    
    g_free (str_uri);
    
    return GNOME_Evolution_Calendar_Success;
}

/* is_loaded handler for the file backend */
static gboolean
cal_backend_file_is_loaded (CalBackend *backend)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;

    cbfile = CAL_BACKEND_FILE (backend);
    priv = cbfile->priv;

    return (priv->icalcomp != NULL);
}

/* is_remote handler for the file backend */
static CalMode
cal_backend_file_get_mode (CalBackend *backend)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;

    cbfile = CAL_BACKEND_FILE (backend);
    priv = cbfile->priv;

    return CAL_MODE_LOCAL;  
}

/* Set_mode handler for the file backend */
static void
cal_backend_file_set_mode (CalBackend *backend, CalMode mode)
{
    cal_backend_notify_mode (backend,
                 GNOME_Evolution_Calendar_Listener_MODE_NOT_SUPPORTED,
                 GNOME_Evolution_Calendar_MODE_LOCAL);
    
}

static CalBackendSyncStatus
cal_backend_file_get_default_object (CalBackendSync *backend, Cal *cal, char **object)
{
    CalComponent *comp;
    
    comp = cal_component_new ();

    switch (cal_backend_get_kind (CAL_BACKEND (backend))) {
    case ICAL_VEVENT_COMPONENT:
        cal_component_set_new_vtype (comp, CAL_COMPONENT_EVENT);
        break;
    case ICAL_VTODO_COMPONENT:
        cal_component_set_new_vtype (comp, CAL_COMPONENT_TODO);
        break;
    case ICAL_VJOURNAL_COMPONENT:
        cal_component_set_new_vtype (comp, CAL_COMPONENT_JOURNAL);
        break;
    default:
        g_object_unref (comp);
        return GNOME_Evolution_Calendar_ObjectNotFound;
    }
    
    *object = cal_component_get_as_string (comp);
    g_object_unref (comp);
 
    return GNOME_Evolution_Calendar_Success;
}

/* Get_object_component handler for the file backend */
static CalBackendSyncStatus
cal_backend_file_get_object (CalBackendSync *backend, Cal *cal, const char *uid, const char *rid, char **object)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;
    CalComponent *comp;

    cbfile = CAL_BACKEND_FILE (backend);
    priv = cbfile->priv;

    g_return_val_if_fail (priv->icalcomp != NULL, GNOME_Evolution_Calendar_InvalidObject);
    g_return_val_if_fail (uid != NULL, GNOME_Evolution_Calendar_ObjectNotFound);
    g_assert (priv->comp_uid_hash != NULL);

    comp = lookup_component (cbfile, uid);
    if (!comp)
        return GNOME_Evolution_Calendar_ObjectNotFound;

    if (rid && *rid) {
        /* FIXME How to retrieve instance */
    }
    
    *object = cal_component_get_as_string (comp);

    return GNOME_Evolution_Calendar_Success;
}

/* Get_timezone_object handler for the file backend */
static CalBackendSyncStatus
cal_backend_file_get_timezone (CalBackendSync *backend, Cal *cal, const char *tzid, char **object)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;
    icaltimezone *zone;
    icalcomponent *icalcomp;

    cbfile = CAL_BACKEND_FILE (backend);
    priv = cbfile->priv;

    g_return_val_if_fail (priv->icalcomp != NULL, GNOME_Evolution_Calendar_NoSuchCal);
    g_return_val_if_fail (tzid != NULL, GNOME_Evolution_Calendar_ObjectNotFound);

    if (!strcmp (tzid, "UTC")) {
        zone = icaltimezone_get_utc_timezone ();
    } else {
        zone = icalcomponent_get_timezone (priv->icalcomp, tzid);
        if (!zone) {
            zone = icaltimezone_get_builtin_timezone_from_tzid (tzid);
            if (!zone)
                return GNOME_Evolution_Calendar_ObjectNotFound;
        }
    }
    
    icalcomp = icaltimezone_get_component (zone);
    if (!icalcomp)
        return GNOME_Evolution_Calendar_InvalidObject;

    *object = g_strdup (icalcomponent_as_ical_string (icalcomp));

    return GNOME_Evolution_Calendar_Success;
}

/* Add_timezone handler for the file backend */
static CalBackendSyncStatus
cal_backend_file_add_timezone (CalBackendSync *backend, Cal *cal, const char *tzobj)
{
    icalcomponent *tz_comp;
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;

    cbfile = (CalBackendFile *) backend;

    g_return_val_if_fail (IS_CAL_BACKEND_FILE (cbfile), GNOME_Evolution_Calendar_OtherError);
    g_return_val_if_fail (tzobj != NULL, GNOME_Evolution_Calendar_OtherError);

    priv = cbfile->priv;

    tz_comp = icalparser_parse_string (tzobj);
    if (!tz_comp)
        return GNOME_Evolution_Calendar_InvalidObject;

    if (icalcomponent_isa (tz_comp) == ICAL_VTIMEZONE_COMPONENT) {
        icaltimezone *zone;

        zone = icaltimezone_new ();
        icaltimezone_set_component (zone, tz_comp);
        if (!icalcomponent_get_timezone (priv->icalcomp, icaltimezone_get_tzid (zone))) {
            icalcomponent_add_component (priv->icalcomp, tz_comp);
            mark_dirty (cbfile);
        }

        icaltimezone_free (zone, 1);
    }

    return GNOME_Evolution_Calendar_Success;
}


static CalBackendSyncStatus
cal_backend_file_set_default_timezone (CalBackendSync *backend, Cal *cal, const char *tzid)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;
    icaltimezone *zone;

    cbfile = CAL_BACKEND_FILE (backend);
    priv = cbfile->priv;

    g_return_val_if_fail (priv->icalcomp != NULL, GNOME_Evolution_Calendar_NoSuchCal);

    /* Look up the VTIMEZONE in our icalcomponent. */
    zone = icalcomponent_get_timezone (priv->icalcomp, tzid);
    if (!zone)
        return GNOME_Evolution_Calendar_ObjectNotFound;

    /* Set the default timezone to it. */
    priv->default_zone = zone;

    return GNOME_Evolution_Calendar_Success;
}

typedef struct {
    GList *obj_list;
    gboolean search_needed;
    const char *query;
    CalBackendObjectSExp *obj_sexp;
    CalBackend *backend;
    icaltimezone *default_zone;
} MatchObjectData;

static void
match_object_sexp (gpointer key, gpointer value, gpointer data)
{
    CalBackendFileObject *obj_data = value;
    MatchObjectData *match_data = data;

    if ((!match_data->search_needed) ||
        (cal_backend_object_sexp_match_comp (match_data->obj_sexp, obj_data->full_object, match_data->backend))) {
        match_data->obj_list = g_list_append (match_data->obj_list,
                              cal_component_get_as_string (obj_data->full_object));
    }
}

/* Get_objects_in_range handler for the file backend */
static CalBackendSyncStatus
cal_backend_file_get_object_list (CalBackendSync *backend, Cal *cal, const char *sexp, GList **objects)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;
    MatchObjectData match_data;

    cbfile = CAL_BACKEND_FILE (backend);
    priv = cbfile->priv;

    g_message (G_STRLOC ": Getting object list (%s)", sexp);

    match_data.search_needed = TRUE;
    match_data.query = sexp;
    match_data.obj_list = NULL;
    match_data.backend = CAL_BACKEND (backend);
    match_data.default_zone = priv->default_zone;

    if (!strcmp (sexp, "#t"))
        match_data.search_needed = FALSE;

    match_data.obj_sexp = cal_backend_object_sexp_new (sexp);
    if (!match_data.obj_sexp)
        return GNOME_Evolution_Calendar_InvalidQuery;

    g_hash_table_foreach (priv->comp_uid_hash, (GHFunc) match_object_sexp, &match_data);

    *objects = match_data.obj_list;
    
    return GNOME_Evolution_Calendar_Success;    
}

/* get_query handler for the file backend */
static void
cal_backend_file_start_query (CalBackend *backend, Query *query)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;
    MatchObjectData match_data;

    cbfile = CAL_BACKEND_FILE (backend);
    priv = cbfile->priv;

    g_message (G_STRLOC ": Starting query (%s)", query_get_text (query));

    /* try to match all currently existing objects */
    match_data.search_needed = TRUE;
    match_data.query = query_get_text (query);
    match_data.obj_list = NULL;
    match_data.backend = backend;
    match_data.default_zone = priv->default_zone;

    if (!strcmp (match_data.query, "#t"))
        match_data.search_needed = FALSE;

    match_data.obj_sexp = query_get_object_sexp (query);
    if (!match_data.obj_sexp) {
        query_notify_query_done (query, GNOME_Evolution_Calendar_InvalidQuery);
        return;
    }

    g_hash_table_foreach (priv->comp_uid_hash, (GHFunc) match_object_sexp, &match_data);

    /* notify listeners of all objects */
    if (match_data.obj_list) {
        query_notify_objects_added (query, (const GList *) match_data.obj_list);

        /* free memory */
        g_list_foreach (match_data.obj_list, (GFunc) g_free, NULL);
        g_list_free (match_data.obj_list);
    }

    query_notify_query_done (query, GNOME_Evolution_Calendar_Success);
}

static gboolean
free_busy_instance (CalComponent *comp,
            time_t        instance_start,
            time_t        instance_end,
            gpointer      data)
{
    icalcomponent *vfb = data;
    icalproperty *prop;
    icalparameter *param;
    struct icalperiodtype ipt;
    icaltimezone *utc_zone;

    utc_zone = icaltimezone_get_utc_timezone ();

    ipt.start = icaltime_from_timet_with_zone (instance_start, FALSE, utc_zone);
    ipt.end = icaltime_from_timet_with_zone (instance_end, FALSE, utc_zone);
    ipt.duration = icaldurationtype_null_duration ();
    
        /* add busy information to the vfb component */
    prop = icalproperty_new (ICAL_FREEBUSY_PROPERTY);
    icalproperty_set_freebusy (prop, ipt);
    
    param = icalparameter_new_fbtype (ICAL_FBTYPE_BUSY);
    icalproperty_add_parameter (prop, param);
    
    icalcomponent_add_property (vfb, prop);

    return TRUE;
}

static icalcomponent *
create_user_free_busy (CalBackendFile *cbfile, const char *address, const char *cn,
               time_t start, time_t end)
{   
    CalBackendFilePrivate *priv;
    GList *l;
    icalcomponent *vfb;
    icaltimezone *utc_zone;
    CalBackendObjectSExp *obj_sexp;
    char *query;
    
    priv = cbfile->priv;

    /* create the (unique) VFREEBUSY object that we'll return */
    vfb = icalcomponent_new_vfreebusy ();
    if (address != NULL) {
        icalproperty *prop;
        icalparameter *param;
        
        prop = icalproperty_new_organizer (address);
        if (prop != NULL && cn != NULL) {
            param = icalparameter_new_cn (cn);
            icalproperty_add_parameter (prop, param);           
        }
        if (prop != NULL)
            icalcomponent_add_property (vfb, prop);     
    }
    utc_zone = icaltimezone_get_utc_timezone ();
    icalcomponent_set_dtstart (vfb, icaltime_from_timet_with_zone (start, FALSE, utc_zone));
    icalcomponent_set_dtend (vfb, icaltime_from_timet_with_zone (end, FALSE, utc_zone));

    /* add all objects in the given interval */
    query = g_strdup_printf ("occur-in-time-range? %lu %lu", start, end);
    obj_sexp = cal_backend_object_sexp_new (query);
    g_free (query);

    if (!obj_sexp)
        return vfb;

    for (l = priv->comp; l; l = l->next) {
        CalComponent *comp = l->data;
        icalcomponent *icalcomp, *vcalendar_comp;
        icalproperty *prop;
        
        icalcomp = cal_component_get_icalcomponent (comp);
        if (!icalcomp)
            continue;

        /* If the event is TRANSPARENT, skip it. */
        prop = icalcomponent_get_first_property (icalcomp,
                             ICAL_TRANSP_PROPERTY);
        if (prop) {
            icalproperty_transp transp_val = icalproperty_get_transp (prop);
            if (transp_val == ICAL_TRANSP_TRANSPARENT ||
                transp_val == ICAL_TRANSP_TRANSPARENTNOCONFLICT)
                continue;
        }
    
        if (!cal_backend_object_sexp_match_comp (obj_sexp, l->data, CAL_BACKEND (cbfile)))
            continue;
        
        vcalendar_comp = icalcomponent_get_parent (icalcomp);
        cal_recur_generate_instances (comp, start, end,
                          free_busy_instance,
                          vfb,
                          resolve_tzid,
                          vcalendar_comp,
                          priv->default_zone);
    }

    return vfb; 
}

/* Get_free_busy handler for the file backend */
static CalBackendSyncStatus
cal_backend_file_get_free_busy (CalBackendSync *backend, Cal *cal, GList *users,
                time_t start, time_t end, GList **freebusy)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;
    gchar *address, *name;  
    icalcomponent *vfb;
    char *calobj;
    GList *l;

    cbfile = CAL_BACKEND_FILE (backend);
    priv = cbfile->priv;

    g_return_val_if_fail (priv->icalcomp != NULL, GNOME_Evolution_Calendar_NoSuchCal);
    g_return_val_if_fail (start != -1 && end != -1, GNOME_Evolution_Calendar_InvalidRange);
    g_return_val_if_fail (start <= end, GNOME_Evolution_Calendar_InvalidRange);

    *freebusy = NULL;
    
    if (users == NULL) {
        if (cal_backend_mail_account_get_default (priv->config_listener, &address, &name)) {
            vfb = create_user_free_busy (cbfile, address, name, start, end);
            calobj = icalcomponent_as_ical_string (vfb);
            *freebusy = g_list_append (*freebusy, g_strdup (calobj));
            icalcomponent_free (vfb);
            g_free (address);
            g_free (name);
        }       
    } else {
        for (l = users; l != NULL; l = l->next ) {
            address = l->data;          
            if (cal_backend_mail_account_is_valid (priv->config_listener, address, &name)) {
                vfb = create_user_free_busy (cbfile, address, name, start, end);
                calobj = icalcomponent_as_ical_string (vfb);
                *freebusy = g_list_append (*freebusy, g_strdup (calobj));
                icalcomponent_free (vfb);
                g_free (name);
            }
        }       
    }

    return GNOME_Evolution_Calendar_Success;
}

typedef struct 
{
    CalBackendFile *backend;
    CalObjType type;    
    GList *deletes;
    EXmlHash *ehash;
} CalBackendFileComputeChangesData;

static void
cal_backend_file_compute_changes_foreach_key (const char *key, gpointer data)
{
    CalBackendFileComputeChangesData *be_data = data;
    
    if (!lookup_component (be_data->backend, key)) {
        CalComponent *comp;

        comp = cal_component_new ();
        if (be_data->type == GNOME_Evolution_Calendar_TYPE_TODO)
            cal_component_set_new_vtype (comp, CAL_COMPONENT_TODO);
        else
            cal_component_set_new_vtype (comp, CAL_COMPONENT_EVENT);

        cal_component_set_uid (comp, key);
        be_data->deletes = g_list_prepend (be_data->deletes, cal_component_get_as_string (comp));

        e_xmlhash_remove (be_data->ehash, key);
    }
}

static CalBackendSyncStatus
cal_backend_file_compute_changes (CalBackendFile *cbfile, CalObjType type, const char *change_id,
                  GList **adds, GList **modifies, GList **deletes)
{
    CalBackendFilePrivate *priv;
    char    *filename;
    EXmlHash *ehash;
    CalBackendFileComputeChangesData be_data;
    GList *i;

    priv = cbfile->priv;

    /* FIXME Will this always work? */
    filename = g_strdup_printf ("%s/%s.db", priv->uri, change_id);
    ehash = e_xmlhash_new (filename);
    g_free (filename);
    
    /* Calculate adds and modifies */
    for (i = priv->comp; i != NULL; i = i->next) {
        const char *uid;
        char *calobj;

        cal_component_get_uid (i->data, &uid);
        calobj = cal_component_get_as_string (i->data);

        g_assert (calobj != NULL);

        /* check what type of change has occurred, if any */
        switch (e_xmlhash_compare (ehash, uid, calobj)) {
        case E_XMLHASH_STATUS_SAME:
            break;
        case E_XMLHASH_STATUS_NOT_FOUND:
            *adds = g_list_prepend (*adds, g_strdup (calobj));
            e_xmlhash_add (ehash, uid, calobj);
            break;
        case E_XMLHASH_STATUS_DIFFERENT:
            *modifies = g_list_prepend (*modifies, g_strdup (calobj));
            e_xmlhash_add (ehash, uid, calobj);
            break;
        }

        g_free (calobj);
    }

    /* Calculate deletions */
    be_data.backend = cbfile;
    be_data.type = type;    
    be_data.deletes = NULL;
    be_data.ehash = ehash;
    e_xmlhash_foreach_key (ehash, (EXmlHashFunc)cal_backend_file_compute_changes_foreach_key, &be_data);

    *deletes = be_data.deletes;

    e_xmlhash_write (ehash);
    e_xmlhash_destroy (ehash);
    
    return GNOME_Evolution_Calendar_Success;
}

/* Get_changes handler for the file backend */
static CalBackendSyncStatus
cal_backend_file_get_changes (CalBackendSync *backend, Cal *cal, CalObjType type, const char *change_id,
                  GList **adds, GList **modifies, GList **deletes)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;

    cbfile = CAL_BACKEND_FILE (backend);
    priv = cbfile->priv;

    g_return_val_if_fail (priv->icalcomp != NULL, GNOME_Evolution_Calendar_NoSuchCal);
    g_return_val_if_fail (change_id != NULL, GNOME_Evolution_Calendar_ObjectNotFound);

    return cal_backend_file_compute_changes (cbfile, type, change_id, adds, modifies, deletes);
}

/* Discard_alarm handler for the file backend */
static CalBackendSyncStatus
cal_backend_file_discard_alarm (CalBackendSync *backend, Cal *cal, const char *uid, const char *auid)
{
    /* we just do nothing with the alarm */
    return GNOME_Evolution_Calendar_Success;
}

static CalBackendSyncStatus
cal_backend_file_create_object (CalBackendSync *backend, Cal *cal, const char *calobj, char **uid)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;
    icalcomponent *icalcomp;
    icalcomponent_kind kind;
    CalComponent *comp;
    const char *comp_uid;
    struct icaltimetype current;
    
    cbfile = CAL_BACKEND_FILE (backend);
    priv = cbfile->priv;

    g_return_val_if_fail (priv->icalcomp != NULL, GNOME_Evolution_Calendar_NoSuchCal);
    g_return_val_if_fail (calobj != NULL, GNOME_Evolution_Calendar_ObjectNotFound);

    icalcomp = icalparser_parse_string ((char *) calobj);
    if (!icalcomp)
        return GNOME_Evolution_Calendar_InvalidObject;

    /* FIXME Check kind with the parent */
    kind = icalcomponent_isa (icalcomp);
    if (kind != ICAL_VEVENT_COMPONENT && kind != ICAL_VTODO_COMPONENT) {
        icalcomponent_free (icalcomp);
        return GNOME_Evolution_Calendar_InvalidObject;
    }

    /* Get the UID */
    comp_uid = icalcomponent_get_uid (icalcomp);
    
    /* check the object is not in our cache */
    if (lookup_component (cbfile, comp_uid)) {
        icalcomponent_free (icalcomp);
        return GNOME_Evolution_Calendar_CardIdAlreadyExists;
    }

    /* Create the cal component */
    comp = cal_component_new ();
    cal_component_set_icalcomponent (comp, icalcomp);

    /* Set the created and last modified times on the component */
    current = icaltime_from_timet (time (NULL), 0);
    cal_component_set_created (comp, &current);
    cal_component_set_last_modified (comp, &current);

    /* Add the object */
    add_component (cbfile, comp, TRUE);

    /* Mark for saving */
    mark_dirty (cbfile);

    /* Return the UID */
    if (uid)
        *uid = g_strdup (comp_uid);

    return GNOME_Evolution_Calendar_Success;
}

static CalBackendSyncStatus
cal_backend_file_modify_object (CalBackendSync *backend, Cal *cal, const char *calobj, 
                CalObjModType mod, char **old_object)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;
    icalcomponent *icalcomp;
    icalcomponent_kind kind;
    const char *comp_uid;
    CalComponent *comp, *old_comp;
    struct icaltimetype current;

    cbfile = CAL_BACKEND_FILE (backend);
    priv = cbfile->priv;
        
    g_return_val_if_fail (priv->icalcomp != NULL, GNOME_Evolution_Calendar_NoSuchCal);
    g_return_val_if_fail (calobj != NULL, GNOME_Evolution_Calendar_ObjectNotFound);

    icalcomp = icalparser_parse_string ((char *) calobj);
    if (!icalcomp)
        return GNOME_Evolution_Calendar_InvalidObject;

    /* FIXME Check kind with the parent */
    kind = icalcomponent_isa (icalcomp);
    if (kind != ICAL_VEVENT_COMPONENT && kind != ICAL_VTODO_COMPONENT) {
        icalcomponent_free (icalcomp);
        return GNOME_Evolution_Calendar_InvalidObject;
    }

    /* Get the uid */
    comp_uid = icalcomponent_get_uid (icalcomp);

    /* Get the object from our cache */
    if (!(old_comp = lookup_component (cbfile, comp_uid))) {
        icalcomponent_free (icalcomp);
        return GNOME_Evolution_Calendar_ObjectNotFound;
    }

    /* Create the cal component */
    comp = cal_component_new ();
    cal_component_set_icalcomponent (comp, icalcomp);
    
    /* Set the last modified time on the component */
    current = icaltime_from_timet (time (NULL), 0);
    cal_component_set_last_modified (comp, &current);

    /* FIXME we need to handle mod types here */

    /* Remove the old version */
    remove_component (cbfile, old_comp);

    /* Add the object */
    add_component (cbfile, comp, TRUE);

    mark_dirty (cbfile);

    if (old_object)
        *old_object = cal_component_get_as_string (comp);

    return GNOME_Evolution_Calendar_Success;
}

/* Remove_object handler for the file backend */
static CalBackendSyncStatus
cal_backend_file_remove_object (CalBackendSync *backend, Cal *cal, const char *uid, const char *rid,
                CalObjModType mod, char **object)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;
    CalComponent *comp;

    cbfile = CAL_BACKEND_FILE (backend);
    priv = cbfile->priv;

    g_return_val_if_fail (priv->icalcomp != NULL, GNOME_Evolution_Calendar_NoSuchCal);
    g_return_val_if_fail (uid != NULL, GNOME_Evolution_Calendar_ObjectNotFound);

    /* FIXME we need to handle mod types here */

    comp = lookup_component (cbfile, uid);
    if (!comp)
        return GNOME_Evolution_Calendar_ObjectNotFound;

    *object = cal_component_get_as_string (comp);
    remove_component (cbfile, comp);

    mark_dirty (cbfile);

    return GNOME_Evolution_Calendar_Success;
}

static gboolean
cancel_received_object (CalBackendFile *cbfile, icalcomponent *icalcomp)
{
    CalComponent *old_comp;

    /* Find the old version of the component. */
    old_comp = lookup_component (cbfile, icalcomponent_get_uid (icalcomp));
    if (!old_comp)
        return FALSE;

    /* And remove it */
    remove_component (cbfile, old_comp);

    return TRUE;
}

typedef struct {
    GHashTable *zones;
    
    gboolean found;
} CalBackendFileTzidData;

static void
check_tzids (icalparameter *param, void *data)
{
    CalBackendFileTzidData *tzdata = data;
    const char *tzid;
    
    tzid = icalparameter_get_tzid (param);
    if (!tzid || g_hash_table_lookup (tzdata->zones, tzid))
        tzdata->found = FALSE;
}

/* Update_objects handler for the file backend. */
static CalBackendSyncStatus
cal_backend_file_receive_objects (CalBackendSync *backend, Cal *cal, const char *calobj,
                  GList **created, GList **modified, GList **removed)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;
    icalcomponent *toplevel_comp, *icalcomp = NULL;
    icalcomponent_kind kind;
    icalproperty_method method;
    icalcomponent *subcomp;
    GList *comps, *l;
    CalBackendFileTzidData tzdata;
    CalBackendSyncStatus status = GNOME_Evolution_Calendar_Success;

    cbfile = CAL_BACKEND_FILE (backend);
    priv = cbfile->priv;

    g_return_val_if_fail (priv->icalcomp != NULL, GNOME_Evolution_Calendar_InvalidObject);
    g_return_val_if_fail (calobj != NULL, GNOME_Evolution_Calendar_InvalidObject);

    /* Pull the component from the string and ensure that it is sane */
    toplevel_comp = icalparser_parse_string ((char *) calobj);
    if (!toplevel_comp)
        return GNOME_Evolution_Calendar_InvalidObject;

    kind = icalcomponent_isa (toplevel_comp);
    if (kind != ICAL_VCALENDAR_COMPONENT) {
        /* If its not a VCALENDAR, make it one to simplify below */
        icalcomp = toplevel_comp;
        toplevel_comp = cal_util_new_top_level ();
        icalcomponent_add_component (toplevel_comp, icalcomp);  
    }

    method = icalcomponent_get_method (toplevel_comp);

    *created = *modified = *removed = NULL;

    /* Build a list of timezones so we can make sure all the objects have valid info */
    tzdata.zones = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);

    subcomp = icalcomponent_get_first_component (toplevel_comp, ICAL_VTIMEZONE_COMPONENT);
    while (subcomp) {
        icaltimezone *zone;
        
        zone = icaltimezone_new ();
        if (icaltimezone_set_component (zone, subcomp))
            g_hash_table_insert (tzdata.zones, g_strdup (icaltimezone_get_tzid (zone)), NULL);
        
        subcomp = icalcomponent_get_next_component (toplevel_comp, ICAL_VTIMEZONE_COMPONENT);
    }   

    /* First we make sure all the components are usuable */
    comps = NULL;
    subcomp = icalcomponent_get_first_component (toplevel_comp, ICAL_ANY_COMPONENT);
    while (subcomp) {
        /* We ignore anything except VEVENT, VTODO and VJOURNAL
           components. */
        icalcomponent_kind child_kind = icalcomponent_isa (subcomp);

        switch (child_kind) {
        case ICAL_VEVENT_COMPONENT:
        case ICAL_VTODO_COMPONENT:
        case ICAL_VJOURNAL_COMPONENT:
            tzdata.found = TRUE;
            icalcomponent_foreach_tzid (subcomp, check_tzids, &tzdata);
            
            if (!tzdata.found) {
                status = GNOME_Evolution_Calendar_InvalidObject;
                goto error;
            }

            if (!icalcomponent_get_uid (subcomp)) {
                status = GNOME_Evolution_Calendar_InvalidObject;
                goto error;
            }
        
            comps = g_list_prepend (comps, subcomp);
            break;
        default:
            /* Ignore it */
            break;
        }

        subcomp = icalcomponent_get_next_component (toplevel_comp, ICAL_ANY_COMPONENT);
    }

    /* Now we manipulate the components we care about */
    for (l = comps; l; l = l->next) {
        subcomp = l->data;
        
        switch (method) {
        case ICAL_METHOD_PUBLISH:
        case ICAL_METHOD_REQUEST:
            /* FIXME Need to see the new create/modify stuff before we set this up */
            break;          
        case ICAL_METHOD_REPLY:
            /* FIXME Update the status of the user, if we are the organizer */
            break;
        case ICAL_METHOD_ADD:
            /* FIXME This should be doable once all the recurid stuff is done */
            break;
        case ICAL_METHOD_COUNTER:
            status = GNOME_Evolution_Calendar_UnsupportedMethod;
            goto error;
            break;          
        case ICAL_METHOD_DECLINECOUNTER:            
            status = GNOME_Evolution_Calendar_UnsupportedMethod;
            goto error;
            break;
        case ICAL_METHOD_CANCEL:
            /* FIXME Do we need to remove the subcomp so it isn't merged? */
            if (cancel_received_object (cbfile, subcomp))
                *removed = g_list_prepend (*removed, g_strdup (icalcomponent_get_uid (subcomp)));
            break;
        default:
            status = GNOME_Evolution_Calendar_UnsupportedMethod;
            goto error;
        }
    }
    g_list_free (comps);
    
    /* Merge the iCalendar components with our existing VCALENDAR,
       resolving any conflicting TZIDs. */
    icalcomponent_merge_component (priv->icalcomp, toplevel_comp);

    mark_dirty (cbfile);

 error:
    g_hash_table_destroy (tzdata.zones);
    
    return status;
}

static CalBackendSyncStatus
cal_backend_file_send_objects (CalBackendSync *backend, Cal *cal, const char *calobj)
{
    /* FIXME Put in a util routine to send stuff via email */
    
    return GNOME_Evolution_Calendar_Success;
}

static icaltimezone *
cal_backend_file_internal_get_default_timezone (CalBackend *backend)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;

    cbfile = CAL_BACKEND_FILE (backend);
    priv = cbfile->priv;

    g_return_val_if_fail (priv->icalcomp != NULL, NULL);

    return priv->default_zone;
}

static icaltimezone *
cal_backend_file_internal_get_timezone (CalBackend *backend, const char *tzid)
{
    CalBackendFile *cbfile;
    CalBackendFilePrivate *priv;
    icaltimezone *zone;

    cbfile = CAL_BACKEND_FILE (backend);
    priv = cbfile->priv;

    g_return_val_if_fail (priv->icalcomp != NULL, NULL);

    if (!strcmp (tzid, "UTC"))
            zone = icaltimezone_get_utc_timezone ();
    else {
        zone = icalcomponent_get_timezone (priv->icalcomp, tzid);
        if (!zone)
            zone = icaltimezone_get_builtin_timezone_from_tzid (tzid);
    }

    return zone;
}

/* Object initialization function for the file backend */
static void
cal_backend_file_init (CalBackendFile *cbfile, CalBackendFileClass *class)
{
    CalBackendFilePrivate *priv;

    priv = g_new0 (CalBackendFilePrivate, 1);
    cbfile->priv = priv;

    priv->uri = NULL;
    priv->file_name = g_strdup ("calendar.ics");
    priv->icalcomp = NULL;
    priv->comp_uid_hash = NULL;
    priv->comp = NULL;

    /* The timezone defaults to UTC. */
    priv->default_zone = icaltimezone_get_utc_timezone ();

    priv->config_listener = e_config_listener_new ();
}

/* Class initialization function for the file backend */
static void
cal_backend_file_class_init (CalBackendFileClass *class)
{
    GObjectClass *object_class;
    CalBackendClass *backend_class;
    CalBackendSyncClass *sync_class;

    object_class = (GObjectClass *) class;
    backend_class = (CalBackendClass *) class;
    sync_class = (CalBackendSyncClass *) class;

    parent_class = (CalBackendSyncClass *) g_type_class_peek_parent (class);

    object_class->dispose = cal_backend_file_dispose;
    object_class->finalize = cal_backend_file_finalize;

    sync_class->is_read_only_sync = cal_backend_file_is_read_only;
    sync_class->get_cal_address_sync = cal_backend_file_get_cal_address;
    sync_class->get_alarm_email_address_sync = cal_backend_file_get_alarm_email_address;
    sync_class->get_ldap_attribute_sync = cal_backend_file_get_ldap_attribute;
    sync_class->get_static_capabilities_sync = cal_backend_file_get_static_capabilities;
    sync_class->open_sync = cal_backend_file_open;
    sync_class->remove_sync = cal_backend_file_remove;
    sync_class->create_object_sync = cal_backend_file_create_object;
    sync_class->modify_object_sync = cal_backend_file_modify_object;
    sync_class->remove_object_sync = cal_backend_file_remove_object;
    sync_class->discard_alarm_sync = cal_backend_file_discard_alarm;
    sync_class->receive_objects_sync = cal_backend_file_receive_objects;
    sync_class->send_objects_sync = cal_backend_file_send_objects;
    sync_class->get_default_object_sync = cal_backend_file_get_default_object;
    sync_class->get_object_sync = cal_backend_file_get_object;
    sync_class->get_object_list_sync = cal_backend_file_get_object_list;
    sync_class->get_timezone_sync = cal_backend_file_get_timezone;
    sync_class->add_timezone_sync = cal_backend_file_add_timezone;
    sync_class->set_default_timezone_sync = cal_backend_file_set_default_timezone;
    sync_class->get_freebusy_sync = cal_backend_file_get_free_busy;
    sync_class->get_changes_sync = cal_backend_file_get_changes;

    backend_class->is_loaded = cal_backend_file_is_loaded;
    backend_class->start_query = cal_backend_file_start_query;
    backend_class->get_mode = cal_backend_file_get_mode;
    backend_class->set_mode = cal_backend_file_set_mode;

    backend_class->internal_get_default_timezone = cal_backend_file_internal_get_default_timezone;
    backend_class->internal_get_timezone = cal_backend_file_internal_get_timezone;
}


/**
 * cal_backend_file_get_type:
 * @void: 
 * 
 * Registers the #CalBackendFile class if necessary, and returns the type ID
 * associated to it.
 * 
 * Return value: The type ID of the #CalBackendFile class.
 **/
GType
cal_backend_file_get_type (void)
{
    static GType cal_backend_file_type = 0;

    if (!cal_backend_file_type) {
        static GTypeInfo info = {
                        sizeof (CalBackendFileClass),
                        (GBaseInitFunc) NULL,
                        (GBaseFinalizeFunc) NULL,
                        (GClassInitFunc) cal_backend_file_class_init,
                        NULL, NULL,
                        sizeof (CalBackendFile),
                        0,
                        (GInstanceInitFunc) cal_backend_file_init
                };
        cal_backend_file_type = g_type_register_static (CAL_TYPE_BACKEND_SYNC,
                                "CalBackendFile", &info, 0);
    }

    return cal_backend_file_type;
}

void
cal_backend_file_set_file_name (CalBackendFile *cbfile, const char *file_name)
{
    CalBackendFilePrivate *priv;
    
    g_return_if_fail (cbfile != NULL);
    g_return_if_fail (IS_CAL_BACKEND_FILE (cbfile));
    g_return_if_fail (file_name != NULL);

    priv = cbfile->priv;
    
    if (priv->file_name)
        g_free (priv->file_name);
    
    priv->file_name = g_strdup (file_name);
}

const char *
cal_backend_file_get_file_name (CalBackendFile *cbfile)
{
    CalBackendFilePrivate *priv;

    g_return_val_if_fail (cbfile != NULL, NULL);
    g_return_val_if_fail (IS_CAL_BACKEND_FILE (cbfile), NULL);

    priv = cbfile->priv;    

    return priv->file_name;
}