# This file is part of the CfgNet module.
#
# This program 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.
#
# This program 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
# this program.  If not, see <https://www.gnu.org/licenses/>.

from typing import List

from git.repo import Repo
from git.objects.commit import Commit
from cfgnet.vcs.git import Git


class GitHistory:
    repo: Repo
    commits: List[Commit]
    commit_index: int

    def __init__(self, git: Git):
        self.repo = git.repo
        self.commits = list(self.repo.iter_commits(rev=self.repo.heads[0]))
        self.commits.reverse()
        self.commit_index = len(self.commits) - 1

    def restore_initial_commit(self) -> Commit:
        initial_commit = self.commits[0]
        if len(self.commits) > 0:
            self.repo.git.checkout(initial_commit)
            self.commit_index = 0

        return initial_commit

    def has_next_commit(self) -> bool:
        return self.commit_index < len(self.commits) - 1

    def next_commit(self) -> Commit:
        self.commit_index += 1

        next_commit: Commit = self.commits[self.commit_index]
        self.repo.git.checkout(next_commit, force=True)

        return next_commit
