import configparser
import os
import subprocess
import sys
import webbrowser
import re

import requests
import colorama
from termcolor import colored

OPENL_GIT_SETTINGS_FILE = 'git-openl.config'
NOT_A_REPO_MESSAGE = 'fatal: not a git repository (or any of the parent directories): .git'


def execute(args, path):
    command = ['git', 'config', '--global']
    command += args
    return subprocess.run(command, cwd=path, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                          universal_newlines=True).stdout


def get_global_gitconfig_dir(path):
    f = execute(['--list', '--show-origin'], path)
    p = execute(['--list'], path)

    f = f.split('\n')[0]
    p = p.split('\n')[0]

    return f[:f.index(p)][5:][:-11]


def get_config_dir(path):
    local_repo_command = \
        subprocess.Popen(['git', 'rev-parse', '--show-toplevel'], cwd=path, stdout=subprocess.PIPE).communicate()[
            0].rstrip().decode('utf-8')
    if local_repo_command == NOT_A_REPO_MESSAGE:
        print(colored("not a git repo", color='red'))
        sys.exit(0)
    # Searching for local settings of openl-plugin
    local_config_dir = os.path.join(local_repo_command, '.git')
    local_config_file = os.path.join(local_config_dir, OPENL_GIT_SETTINGS_FILE)
    # Searching for global settings of openl-plugin
    global_config_dir = get_global_gitconfig_dir(path)
    global_config_file = os.path.join(global_config_dir, OPENL_GIT_SETTINGS_FILE)
    # Local settings are preferable then global
    if os.path.exists(local_config_file):
        return local_config_file
    elif os.path.exists(global_config_file):
        return global_config_file
    else:
        print(colored('settings were not found locally/globally', color='red'))
        sys.exit(0)


if __name__ == "__main__":
    colorama.init()
    workbook_name = ''
    rename_from = rename_to = None
    if not 8 <= len(sys.argv) <= 10:
        print(colored('Unexpected number of arguments', color='red'))
        sys.exit(0)
    if len(sys.argv) == 8:
        _, workbook_name, workbook_b, _, _, workbook_a, _, _ = sys.argv
    if len(sys.argv) == 9:
        _, _, workbook_name, workbook_b, _, _, workbook_a, _, _ = sys.argv
    if len(sys.argv) == 10:
        _, workbook_name, workbook_b, _, _, workbook_a, _, _, _, message = sys.argv
        if message is not None:
            match = re.search('(rename from.*)\n(rename to.*)\n', message)
            if match:
                rename_from = match.group(1)
                rename_to = match.group(2)
    if re.search('\~\$', workbook_name):
        print(f'temporary file {workbook_name} was ignored')
        sys.exit(0)
    print(f'diff in progress for {workbook_name}')
    config = configparser.ConfigParser()
    config_dir = get_config_dir(os.getcwd())
    config.read(config_dir)
    post_url_from_installer = url_from_registry = os.getenv('WebstudioPath')
    post_url_from_config = config['DEFAULT']['comparison_url']
    post_url = post_url_from_config if post_url_from_config != '' else post_url_from_installer

    path_workbook_a = os.path.abspath(workbook_a) if workbook_a != 'nul' and workbook_a != '/dev/null' else None
    path_workbook_b = os.path.abspath(workbook_b) if workbook_b != 'nul' and workbook_b != '/dev/null' else None

    file_after = open(path_workbook_a, 'rb') if path_workbook_a is not None else None
    file_before = open(path_workbook_b, 'rb') if path_workbook_b is not None else None
    response = None
    try:
        files = {'file1': file_before, 'file2': file_after}
        response = requests.post(post_url, files=files, data={'fileName': workbook_name})
        webbrowser.open(response.url, new=2)
        if rename_from is not None:
            print(colored(rename_from, color='white'))
            print(colored(rename_to, color='white'))
        print(colored('Comparison page in browser was opened for: ', color='white'))
        print(colored('a/' + workbook_name, color='white')) if file_after is not None else print(
            colored('a/file was not presented: ' + workbook_name, color='white'))
        print(colored('b/' + workbook_name, color='white')) if file_before is not None else print(
            colored('b/file was not presented: ' + workbook_name, color='white'))
    except requests.exceptions.ConnectionError:
        print(colored('Server is not available', color='red'))
    except webbrowser.Error:
        print(colored('Unable to open a web browser, try accessing this URL manually instead:', color='red'))
        print(colored(response.url, color='red')) if response is not None else print(
            colored("url wasn't generated by server", color='red'))
    except Exception as e:
        print(colored('Something went wrong', color='red'))
        print(e)
    finally:
        file_after.close() if file_after is not None else None
        file_before.close() if file_before is not None else None
