#!/usr/bin/env python3

# Args collect sys arg: (files or directories)
# Args collect commands 

import glob 
import os
import re
import sys

langs   = [
              "grails"
          ]

args    = sys.argv[1:]
options = [x for x in args if x.startswith("-")]
files   = [x for x in args if os.path.exists(x)]
lang    = list(filter(
                 lambda x: x in langs,
                 args
             ))
is_dry_run = "--dry-run" in options

if len(lang) > 1:
    print("\nMultiple languages selected. Please select one.\n")
    sys.exit()

if len(lang) == 0:
    print("\nNo languages selected. Please select one.\n")
    sys.exit()

def read(path):
    try:
        f = open(path)
        content = f.read()
        f.close()
        return content
    except:
        return ''

def not_javascript_contraption(line):
    len(line)

def format_file(file):
    if(is_dry_run == True):
        print(file)
    else:
        content = read(file).split('\n')
        # print(content)
        #
        # according to the desirable pattern,
        # fix the code base
        #
        new_content             = []
        previous_equal_location = 0

        for line in content:
            if(
                (len(line) < 200) and
                (re.search(
                     "(\s{4})+static\s+[a-zA-Z]+\s+=",
                     line
                ) != None)
            ):
                re_equal      = r'[^=]+=[^=]'
                re_prefix     = r'\[[a-z]+\:\s*'
                re_hit_prefix = re.search(re_prefix, line)

                if(re.search(re_equal, line)):
                    previous_equal_location = line.index('=')

                if(re_hit_prefix):
                    line   = re.sub(
                               re_prefix,
                               "\n%s%s" % (
                                   ' ' * previous_equal_location,
                                   re_hit_prefix.group(0)
                               ),
                               line
                           )
                    # print("* " + line)
                    print(line)

def format_directory(path):
    if os.path.isfile(path):
        format_file(path)
    else:
        for _path in glob.glob(path + "/*"):
            format_directory(_path)

for file in files:
    format_directory(file)
