from threading import Lock

from plesk_mail_migrator.core.progress.restore.restore_progress import RestoreProgress
from plesk_mail_migrator.utils.file_utils import write_json_file_consistent


class RestoreProgressFile(RestoreProgress):
    """Class to track progress of mail messages restoration - put the progress to JSON file"""

    def __init__(self, filename):
        self._filename = filename
        self._lock = Lock()
        self._data = {}

    def set_restored_message(self, message_num):
        """Set that mail migrator restores specified message number right now

        :type message_num: int
        :rtype: None
        """
        with self._lock:
            self._data['current_restored_message_num'] = message_num
            self._write()

    def set_stat_restored_messages(self, overall_messages_num, overall_messages_length):
        """Sets appropriate field in restore progress file required for stats

        :type overall_messages_num: int
        :type overall_messages_length: int
        :rtype: None
        """
        with self._lock:
            self._data['restored_overall_messages_num'] = overall_messages_num
            self._data['restored_overall_messages_length'] = overall_messages_length
            self._write()

    def _write(self):
        write_json_file_consistent(self._filename, self._data)
