import zipfile
import sys
from config_manager import ConfigManager
from util.commands import sudo_remove, sudo_move
from util.log import log


class Updater:

    def __init__(self):
        """
        Updates the current installation of the installer
        """
        self.tmp_archive = "/tmp/rasdaman-installer.zip"
        self.tmp_installer = "/tmp/rasdaman-installer"

    def update(self):
        """
        Does the actual update process
        :return: true if it was updated, false otherwise
        :rtype: bool
        """
        if self.needs_to_update():
            self.download_archive()
            self.unzip()
            self.move_files_to_current()
            return True
        return False

    def move_files_to_current(self):
        """
        Removes the current installation files and replaces them with the new
        installer files
        """
        sudo_remove(ConfigManager.installer_directory)
        sudo_move(self.tmp_installer, ConfigManager.installer_directory)

    def unzip(self):
        """
        Unzips the installer
        """
        zfile = zipfile.ZipFile(self.tmp_archive)
        zfile.extractall(self.tmp_installer)

    def download_archive(self):
        """
        Downloads the installer
        """
        installer_url = ConfigManager.installer_url + "rasdaman-installer.zip"
        if sys.version_info[0] < 3:
            import urllib
            urlretrieve = urllib.urlretrieve
        else:
            import urllib.request
            urlretrieve = urllib.request.urlretrieve

        urlretrieve(installer_url, self.tmp_archive)

    def needs_to_update(self):
        """
        Determines if we need to update
        :rtype: bool
        """
        version_url = ConfigManager.installer_url + "version.txt"
        try:
            if sys.version_info[0] < 3:
                import urllib2
                urlopen = urllib2.urlopen
            else:
                import urllib.request
                urlopen = urllib.request.urlopen

            version = urlopen(version_url, timeout=10).read()
        except Exception:
            log.warn("Failed reading URL '" + version_url +
                "', cannot check if the installer needs to be updated.")
            return False
        current_version = tuple(map(int, ConfigManager.version.split(".")))
        server_version = tuple(map(int, version.split(".")))
        if current_version < server_version:
            return True
        return False
