001/*
002 *
003 * Copyright 2021-2025 Florian Schmaus
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smackx.time.packet;
018
019import java.text.ParseException;
020import java.time.ZoneId;
021import java.time.ZonedDateTime;
022import java.util.Calendar;
023
024import org.jivesoftware.smack.XMPPConnection;
025import org.jivesoftware.smack.packet.IqBuilder;
026import org.jivesoftware.smack.packet.IqData;
027
028import org.jxmpp.util.XmppDateTime;
029
030public class TimeBuilder extends IqBuilder<TimeBuilder, Time> implements TimeView {
031
032    private ZonedDateTime zonedDateTime;
033
034    TimeBuilder(IqData iqCommon) {
035        super(iqCommon);
036    }
037
038    TimeBuilder(XMPPConnection connection) {
039        super(connection);
040    }
041
042    TimeBuilder(String stanzaId) {
043        super(stanzaId);
044    }
045
046    @Override
047    public ZonedDateTime getZonedDateTime() {
048        return zonedDateTime;
049    }
050
051    public TimeBuilder set(ZonedDateTime zonedDateTime) {
052        this.zonedDateTime = zonedDateTime;
053        return getThis();
054    }
055
056    /**
057     * Sets the time using UTC formatted String, in the format CCYY-MM-DDThh:mm:ssZ, and the provided timezone
058     * definition in the format (+|-)hh:mm.
059     *
060     * @param utc the time using a formatted String.
061     * @param tzo the time zone definition.
062     * @return a reference to this builder.
063     * @throws ParseException if the provided string is not parsable (e.g. because it does not follow the expected
064     *         format).
065     */
066    public TimeBuilder setUtcAndTzo(String utc, String tzo) throws ParseException {
067        var instant = XmppDateTime.parseDate(utc).toInstant();
068        var zoneId = ZoneId.of(tzo);
069
070        zonedDateTime = instant.atZone(zoneId);
071
072        return getThis();
073    }
074
075    public TimeBuilder setTime(Calendar calendar) {
076        zonedDateTime = ZonedDateTime.ofInstant(calendar.toInstant(), calendar.getTimeZone().toZoneId());
077
078        return getThis();
079    }
080
081    @Override
082    public Time build() {
083        return new Time(this);
084    }
085
086    @Override
087    public TimeBuilder getThis() {
088        return this;
089    }
090}