""" turtlevcs module

This file is part of Turtle.

Turtle 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 3 of the License, or
(at your option) any later version.

Turtle 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 Turtle. If not, see <https://www.gnu.org/licenses/>. 
"""
import os
import sys
import subprocess
import pygit2
from gi.repository import Gio

status_icon_map = {
    pygit2.GIT_STATUS_CURRENT: "emblem-default",
    pygit2.GIT_STATUS_INDEX_NEW: "emblem-new",
    pygit2.GIT_STATUS_INDEX_MODIFIED: "emblem-important",
    pygit2.GIT_STATUS_INDEX_DELETED: "edit-delete",
    pygit2.GIT_STATUS_INDEX_RENAMED: "emblem-symbolic-link",
    pygit2.GIT_STATUS_INDEX_TYPECHANGE: "dialog-question",
    pygit2.GIT_STATUS_WT_NEW: "dialog-question",
    pygit2.GIT_STATUS_WT_MODIFIED: "emblem-important",
    pygit2.GIT_STATUS_WT_DELETED: "edit-delete",
    pygit2.GIT_STATUS_WT_TYPECHANGE: "dialog-question",
    pygit2.GIT_STATUS_WT_RENAMED: "emblem-symbolic-link",
    pygit2.GIT_STATUS_WT_UNREADABLE: "emblem-readonly",
    pygit2.GIT_STATUS_IGNORED: "emblem-dropbox-selsync",
    pygit2.GIT_STATUS_CONFLICTED: "software-update-urgent",
}

delta_status_icon_map = {
    pygit2.GIT_DELTA_ADDED: "emblem-new",
    pygit2.GIT_DELTA_CONFLICTED: "software-update-urgent",
    pygit2.GIT_DELTA_COPIED: "emblem-symbolic-link",
    pygit2.GIT_DELTA_DELETED: "edit-delete",
    pygit2.GIT_DELTA_IGNORED: "emblem-dropbox-selsync",
    pygit2.GIT_DELTA_MODIFIED: "emblem-important",
    pygit2.GIT_DELTA_RENAMED: "emblem-dropbox-selsync",
    pygit2.GIT_DELTA_TYPECHANGE: "dialog-question",
    pygit2.GIT_DELTA_UNMODIFIED: "emblem-default",
    pygit2.GIT_DELTA_UNREADABLE: "emblem-readonly",
    pygit2.GIT_DELTA_UNTRACKED: "dialog-question",
}

VERSION = "0.7"
TURTLE_APP_ID = "de.philippun1.turtle"

STATUS_WT_BITMAP = (pygit2.GIT_STATUS_CONFLICTED +
                    pygit2.GIT_STATUS_WT_DELETED +
                    pygit2.GIT_STATUS_WT_MODIFIED +
                    pygit2.GIT_STATUS_WT_NEW +
                    pygit2.GIT_STATUS_WT_RENAMED +
                    pygit2.GIT_STATUS_WT_TYPECHANGE +
                    pygit2.GIT_STATUS_WT_UNREADABLE)

STATUS_INDEX_BITMAP = (pygit2.GIT_STATUS_INDEX_DELETED +
                       pygit2.GIT_STATUS_INDEX_MODIFIED +
                       pygit2.GIT_STATUS_INDEX_NEW +
                       pygit2.GIT_STATUS_INDEX_RENAMED +
                       pygit2.GIT_STATUS_INDEX_TYPECHANGE)

def has_index_status(status):
    """ check if a status contains an index status """
    index_status = status & STATUS_INDEX_BITMAP
    return index_status > 0, index_status

def has_worktree_status(status):
    """ check if a status contains an index status """
    wt_status = status & STATUS_WT_BITMAP
    return wt_status > 0, wt_status

def get_full_version():
    """ get full version string of turtle """
    try:
        repo = pygit2.Repository(os.path.realpath(__file__))
        return f"{VERSION}-{repo.get(repo.head.target.hex).short_id}"
    except Exception:
        pass
    return VERSION

def launch_dialog(module, args):
    """ helper function to launch a turtle dialog """
    basedir, _ = os.path.split(os.path.dirname(os.path.realpath(__file__)))
    path = os.path.join(basedir, "turtlevcs", "dialogs", module + ".py")

    executable = sys.executable
    if os.path.exists(path):
        if "PYTHON" in list(os.environ.keys()):
            executable = os.environ["PYTHON"]
        subprocess.run([executable, path] + args, cwd=basedir, check=False)

    else:
        path = os.path.join(basedir, "turtlevcs", "dialogs", "__init__.py")
        if os.path.exists(path):
            subprocess.run([executable, path, "turtlevcs module '" +
                           module + "' not available"], cwd=basedir, check=False)


def get_author(repo):
    """ get the author signature """
    if isinstance(repo, pygit2.Repository):
        return repo.default_signature


def get_keypair():
    """ get the ssh keypair """
    settings = get_settings()
    if settings:
        if settings.get_boolean("ssh-instead-agent"):
            key = settings.get_string("ssh-key")
            if len(key) > 0 and os.path.exists(key):
                return pygit2.Keypair("git", f"{key}.pub", key, "")
        else:
            agent = settings.get_string("agent")
            if len(agent) > 0:
                return pygit2.KeypairFromAgent(agent)

    raise UserWarning("no credentials available")

def get_settings():
    """ get the gio settings object """
    source = Gio.SettingsSchemaSource.get_default()
    schema = source.lookup(TURTLE_APP_ID, True)
    if schema is not None:
        settings = Gio.Settings(schema_id=TURTLE_APP_ID)
        return settings

    return None
