# -*- coding: utf-8 -*-
from lektor.pluginsystem import Plugin

from lektor.publisher import Publisher, _patch_git_env
import subprocess
import uuid


class GitPlugin(Plugin):
    name = 'git'
    description = u'manage content via git.'

    def on_setup_env(self, **extra):
        try:
            self.env.add_publisher('git-publish', GitPublisher)
            self.env.add_publisher('git-sync', GitSync)
        except AttributeError:
            from lektor.publisher import publishers
            publishers['git-publish'] = GitPublisher
            publishers['git-sync'] = GitSync


class GitPublisher(Publisher):

    def publish(self, target, credentials=None, **extra):
        env = _patch_git_env({})

        yield "Commiting content directory..."
        subprocess.run(["git", "add", "content"], env=env)
        subprocess.run(["git", "commit", "-m", "Added from preflight"], env=env)

        yield "Pushing to Git ..."
        subprocess.run(["git", "push"], env=env)

        yield "Pulling from Git ..."
        subprocess.run(["git", "pull"], env=env)


        yield "Done"
        return

# pulls master
class GitSync(Publisher):

    def publish(self, target, credentials=None, **extra):
        env = _patch_git_env({})

        yield "Commit trash ..."
        subprocess.run(["git", "add", "content"], env=env)
        subprocess.run(["git", "commit", "-m", "trash"], env=env)

        yield "Checkout reset master ..."
        subprocess.run(["git", "checkout", "-f", "master"], env=env)
        subprocess.run(["git", "reset", "--hard", "origin/master"], env=env)

        yield "Pull Updates"
        subprocess.run(["git", "pull"], env=env)

        yield "Done"
        return