/*
* Copyright © 2025 Alain M. (https://github.com/alainm23/planify)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* 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., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* Authored by: Alain M. <alainmh23@gmail.com>
*/

public class Services.Api : GLib.Object {
    private static Api? _instance;
    public static Api get_default () {
        if (_instance == null) {
            _instance = new Api ();
        }
        return _instance;
    }

    public async Objects.Release? get_latest_release () throws Error {
        var session = new Soup.Session ();
        var message = new Soup.Message ("GET", "https://flathub.org/api/v2/appstream/io.github.alainm23.planify?locale=en");
        
        var response = yield session.send_and_read_async (message, Priority.DEFAULT, null);
        var json_string = (string) response.get_data ();
        
        var parser = new Json.Parser ();
        parser.load_from_data (json_string);
        
        var root_object = parser.get_root ().get_object ();
        
        if (!root_object.has_member ("releases")) {
            return null;
        }
        
        var releases_array = root_object.get_array_member ("releases");
        
        if (releases_array.get_length () == 0) {
            return null;
        }
        
        Json.Object? latest_release_json = null;
        int64 latest_timestamp = 0;
        
        releases_array.foreach_element ((array, index, element) => {
            var release_json = element.get_object ();
            var timestamp = int64.parse (release_json.get_string_member ("timestamp"));
            
            if (timestamp > latest_timestamp) {
                latest_timestamp = timestamp;
                latest_release_json = release_json;
            }
        });
        
        return latest_release_json != null ? new Objects.Release.from_json (latest_release_json) : null;
    }
}
