/*
 * Copyright (C) Birb Developers
 *
 * Birb is the legal property of its developers, whose names are too numerous
 * to list here. Please refer to the AUTHORS file distributed with this source
 * distribution
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation; either version 2.1 of the License, or (at your
 * option) any later version.
 *
 * This library 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 Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, see <https://www.gnu.org/licenses/>.
 */

#include "birbtimezone.h"

#include "birbstr.h"

/******************************************************************************
 * Public API
 *****************************************************************************/

void
birb_time_zone_clear(GTimeZone **timezone_ptr) {
	if(timezone_ptr == NULL || *timezone_ptr == NULL) {
		return;
	}

	g_time_zone_unref(*timezone_ptr);
	*timezone_ptr = NULL;
}

int
birb_time_zone_compare(GTimeZone *tz1, GTimeZone *tz2) {
	gint32 offset1;
	gint32 offset2;

	if(tz1 == NULL && tz2 == NULL) {
		return 0;
	}
	if(tz1 == NULL) {
		return -1;
	}
	if(tz2 == NULL) {
		return 1;
	}

	offset1 = g_time_zone_get_offset(tz1, 0);
	offset2 = g_time_zone_get_offset(tz2, 0);

	if(offset1 < offset2) {
		return -1;
	}

	if(offset1 > offset2) {
		return 1;
	}

	return 0;
}

gboolean
birb_time_zone_equal(GTimeZone *tz1, GTimeZone *tz2) {
	const char *tz1_id;
	const char *tz2_id;

	if(tz1 == NULL && tz2 == NULL) {
		return TRUE;
	}
	if(tz1 == NULL || tz2 == NULL) {
		return FALSE;
	}

	tz1_id = g_time_zone_get_identifier(tz1);
	tz2_id = g_time_zone_get_identifier(tz2);

	return birb_str_equal(tz1_id, tz2_id);
}

gboolean
birb_time_zone_set(GTimeZone **timezone_ptr, GTimeZone *new_timezone) {
	GTimeZone *old = NULL;

	g_return_val_if_fail(timezone_ptr != NULL, FALSE);

	old = *timezone_ptr;

	if(birb_time_zone_equal(old, new_timezone)) {
		return FALSE;
	}

	if(old != NULL) {
		g_time_zone_unref(old);
	}

	if(new_timezone != NULL) {
		*timezone_ptr = g_time_zone_ref(new_timezone);
	} else {
		*timezone_ptr = NULL;
	}

	return TRUE;
}
