#!/usr/bin/python3

import os
import json
import logging
from gi.repository import Gio
from gettext import gettext as _
from SystemUpdater.Core.errors import *
from SystemUpdater.Core.enums import *

class UpdatesAvailable():
    """
    Represent the (potentially partial) results of an unattended-upgrades
    run
    """

    # 更新的缓存数据保存位置 
    UPDATE_AVAILABLE_DATA = "/var/cache/kylin-system-updater/update_available_data.json"

    def __init__(self):
        self.from_revision = None
        self.new_revision = None
        self.available_refs = None
        self.available_metadata = None

        self._deployable = False

        if os.path.exists(self.UPDATE_AVAILABLE_DATA):
            self.read_local()

        def cancelled():
            logging.info("Task has been cancelled...")
        self.cancellable = Gio.Cancellable.new()
        self.cancellable.connect(cancelled)

    def _write_local(self):
        try:
            output_upgrade = {}
            output_upgrade.update({"new_revision":self.new_revision})
            output_upgrade.update({"available_refs":self.available_refs})
            output_upgrade.update({"_deployable":self._deployable})

            #6 产生JSON文件
            with open(self.UPDATE_AVAILABLE_DATA, 'w', encoding='utf-8') as f:
                json.dump(output_upgrade, f, ensure_ascii=False, indent=4)
            logging.info("Write Upgrade data to local json(%s) in shutdown model...",self.UPDATE_AVAILABLE_DATA)
        except Exception as exc:
            logging.error(exc)
    def read_local(self):
        #读取组JSON文件
        try:
            with open(self.UPDATE_AVAILABLE_DATA,'r') as f:
                data = json.load(f)
                self.new_revision = data["new_revision"]
                self.available_refs = data["available_refs"]
                self._deployable = data["_deployable"]
            logging.info("Finished: reading upgrade data from the local file...")
        except Exception as exc:
            logging.error(exc)


    def _get_deployable(self):
        return self._deployable

    def _set_deployable(self, state):
        self._deployable = state
        self._write_local()

    deployable = property(_get_deployable, _set_deployable)