1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5var EXPORTED_SYMBOLS = ["CalIcsSerializer"];
6
7var { cal } = ChromeUtils.import("resource:///modules/calendar/calUtils.jsm");
8
9function CalIcsSerializer() {
10  this.wrappedJSObject = this;
11  this.mItems = [];
12  this.mProperties = [];
13  this.mComponents = [];
14}
15CalIcsSerializer.prototype = {
16  QueryInterface: ChromeUtils.generateQI(["calIIcsSerializer"]),
17  classID: Components.ID("{207a6682-8ff1-4203-9160-729ec28c8766}"),
18
19  addItems(aItems) {
20    if (aItems.length > 0) {
21      this.mItems = this.mItems.concat(aItems);
22    }
23  },
24
25  addProperty(aProperty) {
26    this.mProperties.push(aProperty);
27  },
28
29  addComponent(aComponent) {
30    this.mComponents.push(aComponent);
31  },
32
33  serializeToString() {
34    let calComp = this.getIcalComponent();
35    return calComp.serializeToICS();
36  },
37
38  serializeToInputStream(aStream) {
39    let calComp = this.getIcalComponent();
40    return calComp.serializeToICSStream();
41  },
42
43  serializeToStream(aStream) {
44    let str = this.serializeToString();
45
46    // Convert the javascript string to an array of bytes, using the
47    // UTF8 encoder
48    let convStream = Cc["@mozilla.org/intl/converter-output-stream;1"].createInstance(
49      Ci.nsIConverterOutputStream
50    );
51    convStream.init(aStream, "UTF-8");
52
53    convStream.writeString(str);
54    convStream.close();
55  },
56
57  getIcalComponent() {
58    let calComp = cal.getIcsService().createIcalComponent("VCALENDAR");
59    cal.item.setStaticProps(calComp);
60
61    // xxx todo: think about that the below code doesn't clone the properties/components,
62    //           thus ownership is moved to returned VCALENDAR...
63
64    for (let prop of this.mProperties) {
65      calComp.addProperty(prop);
66    }
67    for (let comp of this.mComponents) {
68      calComp.addSubcomponent(comp);
69    }
70
71    for (let item of cal.iterate.items(this.mItems)) {
72      calComp.addSubcomponent(item.icalComponent);
73    }
74
75    return calComp;
76  },
77};
78