# -*- coding: utf-8 -*-
from setuphelpers import *
import tarfile

app_name = "nodejs"
bin_path = makepath("/", "usr", "local", "bin")
app_path = "/opt/nodejs"

def extract_tar_gz(filename, path="."):
    with tarfile.open(filename, "r:xz") as tar:
        result = tar.extractall(path)

def install():
    archive_name = glob.glob("node-v*-darwin-arm64.tar.xz")[0]

    archive_len = len(archive_name) - len('.tar.xz')
    extracted_folder = archive_name[:archive_len]

    # Removing of symlink
    if isfile(makepath(bin_path, "node" )):
        remove_file(makepath(bin_path, "node" ))

    if isfile(makepath(bin_path, "npm" )):
        remove_file(makepath(bin_path, "npm" ))  

    #Delete older version 
    if isdir(app_path):
        remove_tree(app_path)

    #Extracting archive to app_path
    print(f"Extracting: {archive_name}")
    extract_tar_gz(archive_name, path= app_path)

    #Path to node and npm files 
    node_app = makepath(app_path, extracted_folder, "bin", "node")
    npm_app = makepath(app_path, extracted_folder, "lib", "node_modules", "npm", "bin", "npm-cli.js")

    # Creating symbolic links of node and npm-cli.js to /usr/local/bin
    print(f"Creating alias in path")
    os.symlink(node_app, makepath(bin_path, "node"))
    os.symlink(npm_app, makepath(bin_path, "npm"))

def uninstall():

    # Removing of symlink
    if isfile(makepath(bin_path, "node" )):
        remove_file(makepath(bin_path, "node" ))

    if isfile(makepath(bin_path, "npm" )):
        remove_file(makepath(bin_path, "npm" ))    

    # Removing app directory
    if isdir(app_path):
        print(f"Removing application directory: {app_path}")
        remove_tree(app_path)
