import time
import os
import config
from celery import shared_task
from app import db
from misc_utils import *
from models import *
from smtplib import SMTP


@shared_task(ignore_result=False)
def send_notification(notification_id, users, level):
    notification = db.session.get(Notification, notification_id)

    for user in users:
        db.session.add(UserNotification(db.session.get(User, user), notification, level))
    db.session.commit()

    return 0  # notification sent successfully


@shared_task(ignore_result=False)
def merge_heads(head_route, head_branch, base_route, base_branch):
    server_repo_location = os.path.join(config.REPOS_PATH, base_route.lstrip("/"))
    if not os.path.isdir(server_repo_location):
        raise FileNotFoundError(f"Repo {server_repo_location} not found, cannot merge.")

    if base_route == head_route:
        git_command(server_repo_location, b"", "checkout", f"{base_branch}")
        out, err = git_command(server_repo_location, b"", "merge", "--no-ff", f"heads/{head_branch}", return_err=True)

        return out, err

    remote_url = os.path.join(config.BASE_DOMAIN, "git", base_route.lstrip("/"))

    git_command(server_repo_location, b"", "remote", "add", "NEW", remote_url)
    git_command(server_repo_location, b"", "remote", "update")
    git_command(server_repo_location, b"", "checkout", f"{base_branch}")
    git_command(server_repo_location, b"", "merge", "--allow-unrelated-histories", f"NEW/{head_branch}")
    git_command(server_repo_location, b"", "remote", "rm", "NEW")
