/* DocumentManager.vala
 *
 * Copyright 2023 Diego Iván <diegoivan.mae@gmail.com>
 *
 * 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, see <http://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 */

public sealed class PaperClip.Services.DocumentManager : Object {
    public bool changed { get; private set; default = false; }
    private Document _document;
    public Document document {
        get {
            return _document;
        }
        set {
            disconnect_document ();

            _document = value;
            changed = false;

            document.notify.connect (on_doc_changed);
            document.keywords.items_changed.connect (on_doc_changed);
            document.keyword_changed.connect (on_doc_changed);
        }
    }

    public async void save (string? uri = null) {
        yield document.save (uri ?? document.original_file.get_uri ());
        changed = false;
    }

    private void disconnect_document () {
        if (document == null) {
            return;
        }
        document.notify.disconnect (on_doc_changed);
        document.keywords.items_changed.disconnect (on_doc_changed);
        document.keyword_changed.disconnect (on_doc_changed);
    }

    private void on_doc_changed () {
        changed = true;
    }
}
