#!/usr/bin/python3
 
from pnpm import abs_path

import os
import numpy as np
from rich import print
import rglob
import subprocess as sb
import sys

pkg = "untitled"

if len(sys.argv) < 2:
    print("[bold green] Specify package name: ")
    pkg = input("- ")
else:
    pkg = sys.argv[1]
    
pkg = os.getcwd() + '/' + pkg 

def lsdir(folder):
    return [ f.path for f in os.scandir(folder) if f.is_dir() ]


def ls(path):
    return rglob.rglob(path, "*") + rglob.rglob(path, ".*")

def add_file(file):
    print(file)

def walk(walk_path):
    dirs = lsdir(walk_path)
    files = []
    if (dirs is not None):
        files = files + [ walk(_dir) for _dir in dirs ]
        
    for file in ls(walk_path):
        files.append(file)
        
    ary =  np.array(files)
    return ary.flatten()
    
def pkgify(string):
    return string.replace("-_pkg__art", pkg).replace("-_pkg__", pkg)

def read(file):
    content = None
    with open(file, "r") as f:
        content = f.read()
        f.close()
        
    return content
        
def generate(file, content):
    with open(file, "w") as f:
        f.write(content)
        f.close()
        
os.mkdir(pkg)
os.mkdir(pkg + "/src")

files = walk(abs_path('/generator/-_pkg__'))
print(files)

# sb.call(f"cd {pkg}", shell=True)

for file in files:
    print(file)
    file_name = pkgify(file)
    print(f"generating {file_name}")
    content = pkgify(read(file))
    generate(file_name, content)


def r(command):
    sb.call(command.strip().replace("\n", " && "), shell=True)

os.chdir(pkg)

pkgmngr = 'yarn'
lock_file = "yarn.lock" if pkgmngr == 'yarn' else 'package-lock.json'

if (pkgmngr == 'yarn'): r("yarn set version berry")

r(f"""
    virtualenv .{pkg}_env
    mkdir src/icons docs src/styles
    mv index.html docs/index.html
    touch {lock_file} src/index.js 
    {pkgmngr} install
    source setup {pkgmngr}
""")

