# -*- coding: utf-8 -*-
# ===============================================================================
#
#
# Copyright (c) 2015 IST-SUPSI (www.supsi.ch/ist)
#
# 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 2 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
#
# ===============================================================================
import os
import linuxUi
import version
import platform

from PyQt4.QtGui import QApplication, QMessageBox
import sys

pwd = None
proxy = None


def set_pwd():
    """
        Open UI to ask sudo password
    """

    # QApplication(sys.argv)
    global pwd
    global proxy

    pass_ui = linuxUi.LinuxDialog()
    pass_ui.show()

    if pass_ui.exec_():
        pwd = pass_ui.get_pwd()
        if pass_ui.get_proxy():
            proxy = '--proxy="{}"'.format(pass_ui.get_proxy())
        else:
            proxy = ""

        print proxy

    pass_ui.close()
    del pass_ui


def del_pwd():

    global pwd
    global proxy
    pwd = None
    proxy = None
    del pwd
    del proxy


def install_pip():
    """
        install pip from ppa
    """

    if not pwd:
        set_pwd()
    res = os.system('echo {} | sudo -S apt-get install python-pip -y'.format(pwd))

    if res != 0:
        QMessageBox.warning(None, "Problem during installation", "Problem installing pip")
        return False
    return True


def install_numpy():
    """
        install numpy from pip
    """
    if not pwd:
        set_pwd()
    res = os.system('echo {} | sudo -S python -m pip install --upgrade numpy=={} {}'.format(pwd, version.numpy, proxy))

    if res != 0:
        QMessageBox.warning(None, "Problem during installation", "Problem installing numpy")
        return False
    return True


def install_missing_dep(package):
    """
        install missing dependencies
    """
    packages = ""

    release = platform.linux_distribution()[1]

    for dep in package.keys():

        if package[dep] or dep == 'pip' or dep == 'numpy':
            continue

        if dep == "pandas":
            packages += " pandas=={}".format(version.pandas)
        elif dep == "flopy":
            packages += " flopy=={}".format(version.flopy)
        else:
            if dep == 'seaborn' and release >= '16.04':
                continue
            else:
                packages += " {}".format(dep)

    if len(packages) == 0:
        del_pwd()
        write_file(package)
        return

    if not pwd:
        set_pwd()

    res = os.system('echo {} | sudo -S python -m pip install --upgrade{} {}'.format(pwd, packages, proxy))

    if res == 0:
        del_pwd()
        write_file(package)
        QMessageBox.warning(None, "Installation done", "FREEWAT plugin is ready to use!")
    else:
        # QApplication(sys.argv)
        QMessageBox.warning(None, "Problem during installation", "Problem during installation, please try again")


def write_file(package):
    """
        Write file to confirm that dependecies are installed
    """
    with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'install.txt'), 'w') as f:
        import json
        string = json.dumps(package, indent=4, separators=(',', ': '))
        f.write(string)
        f.close()
