"""
This file called from maya and other dcc apps using python2 directly
Don't add unnecessarry functionality here and update with care.
"""
import os
import json
import subprocess


def append_to_json(json_path, section, key, val):
    """
    :param json_path: path to json file in current workspace
    :param section: can be only 'repath' or 'pin'
    :param path_from:
    :param path_to:
    """

    with open(json_path, 'r') as f:
        try:
            data = json.load(f)
        except ValueError:
            data = {}

    section_data = data.setdefault(section, {})
    section_data[key] = val

    with open(json_path, 'w') as f:
        json.dump(data, f, indent=4, sort_keys=True)


def remove_from_json(json_path, section, key):
    """
    :param json_path: path to json file in current workspace
    :param section: can be only 'repath' or 'pin'
    :param path_from:
    :param path_to:
    """

    with open(json_path, 'r') as f:
        try:
            data = json.load(f)
        except ValueError:
            data = {}

    section_data = data.get(section)
    if not section_data:
        return

    section_data.pop(key, None)

    with open(json_path, 'w') as f:
        json.dump(data, f, indent=4, sort_keys=True)


def get_workspace_json_path():
    """
    Get json path with repaths and pins for workspace if any set
    :return: str, path to json
    """
    workspace = os.environ.get('WORKSPACE')
    json_path = os.environ.get('WREF_RESOLVER_WORKSPACE')
    if workspace and json_path:
        return json_path
    else:
        print('No workspace set')


def __run_command(args):
    _env = os.environ.copy()
    if 'PYTHONPATH' in _env:
        _env.pop("PYTHONPATH")
    if 'QT_PREFERRED_BINDING' in _env:
        _env.pop('QT_PREFERRED_BINDING')
    subprocess.call(args,
                    shell=True,
                    env=_env)


def repath(path_from, path_to):
    """
    Add repath for current workspace if it's set
    :param path_from: str
    :param path_to: str
    """
    args = [os.path.expandvars('$WIZART_DESKTOP/wizart_desktop.exe'), '--repath', path_from, path_to]
    __run_command(args)


def pin(path, version):
    """
    Add pin for current workspace if it's set
    :param path: str
    :param version: str
    """
    args = [os.path.expandvars('$WIZART_DESKTOP/wizart_desktop.exe'), '--pin', path, version]
    __run_command(args)


def remove_repath(path_from):
    """
    Add pin for current workspace if it's set
    :param path: str
    :param version: int
    """
    args = [os.path.expandvars('$WIZART_DESKTOP/wizart_desktop.exe'), '--remove_repath', path_from]
    __run_command(args)


def remove_pin(path):
    """
    Add pin for current workspace if it's set
    :param path: str
    :param version: int
    """
    args = [os.path.expandvars('$WIZART_DESKTOP/wizart_desktop.exe'), '--remove_pin', path]
    __run_command(args)


def create_workspace(path, title=None):
    """
    Create workspace in database, if path is not exist - create it,
    if config-json for wref was not created - create it
    :param title:
    :param path:
    :return:
    """
    args = [os.path.expandvars('$WIZART_DESKTOP/wizart_desktop.exe'), '--create_workspace', path, title]
    __run_command(args)


def remove_workspace(path):
    """
    Search workspace with path and if it exists remove workspace from database. If it was set as current - unset.
    Folder of workspace and any files in it will not be removed. You need to do it by yourself if necessary.
    :param path: path of workspace
    """
    args = [os.path.expandvars('$WIZART_DESKTOP/wizart_desktop.exe'), '--remove_workspace', path]
    __run_command(args)


def set_workspace(path, update_env_vars = False):
    """
    Set workspace by path. Workspace have to exist at that moment
    Warning: if you set workspace in some application, ex. Maya,
    then after setting workspace you need to reopen this application with Wizart Desktop.
    Otherwise you are working in previous workspace
    :param path: path to existing workspace
    """
    args = [os.path.expandvars('$WIZART_DESKTOP/wizart_desktop.exe'), '--set_workspace', path]
    __run_command(args)
    if update_env_vars is True:
        os.environ["WORKSPACE"] = path
        os.environ["WREF_RESOLVER_WORKSPACE"] = os.path.join(path, 'workspace.json')


def unset_workspace(update_env_vars = False):
    """
    Unset workspace by path.
    Warning: if you unset workspace in some application, ex. Maya,
    then after unsetting you need to reopen this application with Wizart Desktop.
    Otherwise you are working in previous workspace
    """
    args = [os.path.expandvars('$WIZART_DESKTOP/wizart_desktop.exe'), '--unset_workspace']
    __run_command(args)
    if update_env_vars is True:
        if "WORKSPACE" in os.environ:
            del os.environ["WORKSPACE"]
        if "WREF_RESOLVER_WORKSPACE" in os.environ:
            del os.environ["WREF_RESOLVER_WORKSPACE"]


if __name__ == "__main__":
    append_to_json('d:/test_examples/test_workspaces/1/workspace.json', 'repath', 'path1', 'path2')
    append_to_json('d:/test_examples/test_workspaces/1/workspace.json', 'pin', 'path1', 2)

    remove_from_json('d:/test_examples/test_workspaces/1/workspace.json', 'repath', 'path1')
    remove_from_json('d:/test_examples/test_workspaces/1/workspace.json', 'pin', 'path1')
