"""
fourGive is script that git clones/pulls git projects.
It allows you to move projects in a special directory.
You can create 'aliases' to reuse projects under other pseudonyms or links.
It uses fourGet to redirect aliases to actual git projects.
"""

### Import libs with weird names 
import sys, os
import subprocess, re
import sys, tarfile, stat 
import hashlib, time

import os, pathlib
import arrow, time
from pathlib import Path

from datetime import datetime, timedelta
import pytz
from relative_datetime import DateTimeUtils

from forgy import fourGet


def cmd(command):
    with subprocess.Popen(command, shell=True) as process:
        process.communicate()

def execute_command(command):
    """
        Execute a command and return output, errors and status code.
        Note: Copied from transpkg.diffTools, when editing sync with the original.
    """
    with subprocess.Popen(
        command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
        shell=True) as process:
        stdout, stderr = process.communicate()
        # Output, Errors, Exit/Status Code
        return {
            "output": stdout.decode().rstrip(),
            "errors": stderr.decode().rstrip(),
            "status": process.returncode,
            "command": command
            }
        

def listFiles(path):
    tagged_root_dir = pathlib.Path(path)
    return tagged_root_dir.resolve().glob('**/*')

def sortFilesByTime(path):
    return sorted(listFiles(path), key=os.path.getctime)

def findNewestFile(path):
    result = max(listFiles(path), key=os.path.getctime)
    return (result, os.path.getctime(result))


def findOldestFile(path):
    result = min(listFiles(path), key=os.path.getctime)
    return (result, os.path.getctime(result))


def pull(url, days=-7, hours=+5):
    gitPath = fourGet.fourSources / fourGet.hashForgySource(url)
    path = os.path.realpath(gitPath.absolute())
    gitHome = Path(gitPath / ".git")
    
    print(arrow.now() - timedelta(days=1))
    critical_time = arrow.now().shift(hours=hours).shift(days=days)
    print(critical_time.int_timestamp)
    time_at_hand = time.gmtime()
    print("  -==================tm mon: ", critical_time)
    if os.path.isdir(path):
        print(path)
        item_time = arrow.get(gitHome.stat().st_mtime)
        time_epoch = time.gmtime(item_time.int_timestamp)
        
        print("It's been %d years, %d months, %d days and %d hours, %d  minutes, %d seconds ago" % (time_at_hand.tm_year - time_epoch.tm_year, time_at_hand.tm_mon - time_epoch.tm_mon , time_at_hand.tm_mday - time_epoch.tm_mday, time_at_hand.tm_hour - time_epoch.tm_hour, time_at_hand.tm_min - time_epoch.tm_min, time_at_hand.tm_sec - time_epoch.tm_sec))
        print(item_time.int_timestamp)
        if item_time < critical_time :
            cmd(f"cd '{path}'; git pull")
        else:
            print("4g: pull: Git Project was already refreshed this week.")
    else:
        # only if not fresh:
        cmd(f"git clone '{url}' '{gitPath}'")



def install():
    """Install/Update anom's main projects.
    Do not use this daily."""
    # TODO: prevent refreshing git sources on daily bases.
    # To force frequent updates use --force-pull key
    pull("https://codeberg.org/anom/transpkg")
    pull("https://codeberg.org/anom/4g")
    # pull("https://codeberg.org/anom/mfs")
    # pull("https://codeberg.org/anom/upen")
    # pull("https://github.com/package-url/packageurl-python")

