"""
This file called from maya and other dcc apps using python2 directly
Don't add unnecessarry functionality here and update with care.
"""
import sys
from Qt import QtCore
import pickle
from wizart import prodtrack_api
from wizart import assetvcs_api
import requests.utils
import requests
from wizart.desktop import utils
import subprocess
import os
import logging
import json

log = logging.getLogger("wizart_desktop")


class WizartDesktopAuthError(Exception):
    pass


def save_cookies_in_settings(cookies, service):
    cookiejar_dict = requests.utils.dict_from_cookiejar(cookies)
    serialized_cookiejar_dict = json.dumps(cookiejar_dict)
    settings = QtCore.QSettings("Wizart Animation", "Desktop")
    settings.setValue(service, serialized_cookiejar_dict)


def auth_to_prodtrack_and_save():
    username = utils.get_user()
    if username:
        password = utils.get_password(username)
        if password:
            session = prodtrack_api.Session()
            try:
                session.login(username, password)
            except prodtrack_api.ProdTrackError as e:
                raise WizartDesktopAuthError("Failed to login to Prodtrack Service %s" % e)
            except requests.ConnectionError:
                log.warning("Failed to login to Prodtrack Service, ConnectionError")
                return False

            save_cookies_in_settings(session.get_request_session().cookies, "prodtrack_cookiejar")
            log.info("Successfully Logged to Prodtrack Service")
            return True
        else:
            log.warning("Failed to login to Prodtrack Service, no password specified")
    else:
        log.warning("Failed to login to Prodtrack Service, no username specified")


def auth_to_fs_ctrl_and_save():
    username = utils.get_user()
    if username:
        password = utils.get_password(username)
        if password:
            session = requests.Session()
            try:
                response = session.post("http://fs_ctrl.burut.net/login", json=dict(login = username, password = password))
            except requests.ConnectionError:
                log.warning("Failed to login to Filesystem Ctrl Service, ConnectionError")
                return False
            if response.status_code != 200:
                raise WizartDesktopAuthError("Failed to login to Filesystem Ctrl Service %s" % str(response) )

            save_cookies_in_settings(session.cookies, "fs_ctrl_cookiejar")
            log.info("Successfully Logged to Filesystem Ctrl Service")
            return True
        else:
            log.warning("Failed to login to Filesystem Ctrl Service, no password specified")
    else:
        log.warning("Failed to login to Filesystem Ctrl Service, no username specified")


def auth_to_assetvcs_and_save():
    username = utils.get_user()
    if username:
        password = utils.get_password(username)
        if password:
            session = assetvcs_api.Session()
            try:
                session.login(username.encode(), password.encode())
            except assetvcs_api.AssetVCSPermissionError as e:
                raise WizartDesktopAuthError("Failed to login to Asset VCS Service %s" % e )
            except requests.ConnectionError:
                log.warning("Failed to login to Asset VCS Service, ConnectionError")
                return False
                
            save_cookies_in_settings(session.get_request_session().cookies, "assetvcs_cookiejar")
            log.info("Successfully Logged to Asset VCS Service")
            return True
        else:
            log.warning("Failed to login to Asset VCS Service, no password specified")
    else:
        log.warning("Failed to login to Asset VCS Service, no username specified")


def get_cookies_from_settings(service):
    settings = QtCore.QSettings("Wizart Animation", "Desktop")
    cookiejar_serialized = settings.value(service)
    if cookiejar_serialized:
        try:
            cookiejar_dict = json.loads(cookiejar_serialized)
        except ValueError:
            # relogin if problems occurred
            return
        return requests.utils.cookiejar_from_dict(cookiejar_dict)


def get_prodtrack_session():
    cookie_jar = get_cookies_from_settings("prodtrack_cookiejar")
    if cookie_jar:
        session = prodtrack_api.Session(cookie_jar = cookie_jar)
        return session


def get_prodtrack_user_info():
    session = get_prodtrack_session()
    log = logging.getLogger("wizart_desktop")
    if session:
        try:
            return session.get_user_info()
        except Exception as e:
            log.warning(str(e))
            return {}
    return {}


def get_assetvcs_session():
    cookie_jar = get_cookies_from_settings("assetvcs_cookiejar")
    if cookie_jar:
        session = assetvcs_api.Session(cookie_jar = cookie_jar)
        return session


def get_fs_ctrl_session():
    cookie_jar = get_cookies_from_settings("fs_ctrl_cookiejar")
    if cookie_jar:
        session = requests.Session()
        session.cookies = cookie_jar
        return session


def wizart_desktop_update_auth():
    """
    Used from host app
    """
    _env = os.environ.copy()
    if 'QT_PREFERRED_BINDING' in _env:
        _env.pop('QT_PREFERRED_BINDING')
    if 'PYTHONPATH' in _env:
        _env.pop("PYTHONPATH")
    subprocess.call([os.path.expandvars('$WIZART_DESKTOP/wizart_desktop.exe'), '--update_auth'], shell=True, env=_env)
