from IPython.core.magic import (
    Magics,
    magics_class,
    line_magic,
)
import github
import pyperclip


@magics_class
class GistMagic(Magics):
    def __init__(self, shell, token=None):
        super(GistMagic, self).__init__(shell)

        if not token:
            print("\nError! Please add token. -> https://github.com/settings/tokens")

        self.token = token

    @line_magic
    def gistmagic(self, line):
        """
        Upload code to gist

        Usage:\\
            %load_ext gistmagic
            %gistmagic -X  (%gistmagic -5 / %gistmagic -25)

        The argument -X is representing the last X In/Out sequences
        """
        if not self.token:
            print("\nPlease add token and reload: %reload_ext gistmagic")
            return

        try:
            assert line.startswith("-")
        except AssertionError:
            print("\nMissing - before the amount of lines to extract. Ex. %gistmagic -10")
            return

        try:
            n = int(line.lstrip("-"))
        except ValueError:
            print("\nLines need to be integer.")
            return

        if n == 0:
            print("\nCan't go back 0 lines")
            return
        elif n == 1:
            n = 2

        SubIn = self.shell.user_ns["In"][-n:]
        Out = self.shell.user_ns["Out"]
        len_in = len(self.shell.user_ns["In"]) - 1
        data = ""

        try:
            for l in range(1, n):
                data = (
                    data
                    + f"In [{l}]: {SubIn[l-1]}<br/>"
                )
                if Out.get((len_in-n)+l) is not None:
                    data = (
                        data
                        + f"Out [{l}]: {Out.get((len_in-n)+l)}<br/><br/>"
                    )
        except IndexError:
            print("Getting everything from the start of the current session.")

        try:
            g = github.Github(self.token)
            gu = g.get_user()
            gist = gu.create_gist(
                True,
                {"snippet.md": github.InputFileContent(content=data)},
                description="Generated by Gist Magic",
            )
            print(f"\n{gist.html_url}\n")
            try:
                pyperclip.copy(gist.html_url)
                print("copied to clipboard!\n")
            except pyperclip.PyperclipException:
                pass
            return
        except github.BadCredentialsException:
            print("\n The provided Gist token failed to authenticate with GutHub")
