# -*- coding: utf-8 -*-

import subprocess
from ddans.single.manager import SManager


class SGitter(SManager):

    def get_branch_name(self):
        try:
            # 运行 git 命令获取当前分支名称
            result = subprocess.run(
                ['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                check=True)
            branch_name = result.stdout.strip()
            return branch_name if branch_name else None
        except subprocess.CalledProcessError:
            # 捕捉到 git 命令错误时返回 None
            return None

    def get_latest_commit_hash(self):
        try:
            # 最近提交的 hash 值
            result = subprocess.run(['git', 'rev-parse', 'HEAD'],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE,
                                    text=True,
                                    check=True)
            return result.stdout.decode('utf-8').strip()
        except subprocess.CalledProcessError:
            # 捕捉到 git 命令错误时返回 None
            return ""

    def get_commit_details(commit_hash):
        try:
            # 最近提交的 hash 值
            result = subprocess.run(
                ['git', 'show', '-s', '--format=%cn,%ce,%s', commit_hash],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                check=True)
            details = result.stdout.decode('utf-8').strip().split(',')
            return {
                'name': details[0],
                'email': details[1],
                'message': ','.join(details[2:])
            }
        except subprocess.CalledProcessError:
            # 捕捉到 git 命令错误时返回 None
            return None

    @property
    def branch_name(self):
        return self.get_data("branch_name")

    def update_branch(self):
        name = self.get_branch_name()
        self.set_data("branch_name", name)
