#!/usr/bin/python3
"""
Homework check script.

Is it a good idea to make it open?
"""
import os
import sys
import ogr
from ogr.abstract import PRStatus
from ogr.exceptions import GitlabAPIException


class Homework:
    pass


class Item:
    def __init__(self, gitlab_service: ogr.GitlabService,  username: str):
        self.gitlab_service = gitlab_service
        self.username = username
        self.project = gitlab_service.get_project(namespace="redhat/research", repo="mastering-git")


class HasForkedMainRepo(Item):
    def check(self):
        try:
            # this doesn't do any calls yet
            fork = self.gitlab_service.get_project(repo="mastering-git", namespace=self.username)
            # this does
            fork.get_branches()
        except GitlabAPIException:
            return False
        else:
            return True


class HasPubkey(Item):
    def check(self):
        user = self.gitlab_service.gitlab_instance.users.list(username=self.username)[0]
        try:
            keys = user.keys.list()
            print(keys)
        except GitlabAPIException:
            return False
        else:
            return bool(keys)


class MRExists(Item):
    def check(self):
        prs = self.project.get_pr_list(PRStatus.all)
        for pr in prs:
            if pr.author == self.username:
                if pr.source_branch == 'main':
                    # we could halt here but there may be more MRs
                    # anyway, the request is to send the MR NOT from main
                    continue
                return True
        return False


class Homework1(Homework):
    items = (HasForkedMainRepo, HasPubkey)


class Homework2(Homework):
    items = (MRExists, )


def check_one(gitlab_username: str):
    gl = ogr.GitlabService(token=os.environ["GITLAB_TOKEN"])
    for HWKls in (Homework1, Homework2):
        for ItKls in HWKls.items:
            item = ItKls(gl, gitlab_username)
            print(f"{item.__class__.__name__}: {item.check()}")


# TODO: run for all course participants

if __name__ == '__main__':
    sys.exit(check_one(sys.argv[1]))
