#!/usr/bin/env python
# -*- coding: utf-8 -*-

import argparse
import re
import os
import sys

CUR_FILE_DIR = os.path.abspath(os.path.dirname(__file__));

def open_file(filepath, mode, encoding):
    if sys.version_info.major == 3:
        return open(filepath, mode, encoding=encoding)
    else:
        import codecs
        return codecs.open(filepath, mode, encoding)


class FileInsertHandler(object):
    def __init__(self, filepath):
        self.lines = []
        self.thrd_libs = {}
        self.mark_prefix = '//---SyncByPyScript---'
        self.has_changed = False
        with open_file(filepath, 'r', 'utf-8') as fp:
            self.lines = fp.readlines()
            fp.close()

        expression = self.mark_prefix + "([\w+]+)-(start|end)"
        for i in range(0,len(self.lines)):
            line = self.lines[i]
            m_ret = re.match(expression, line)
            if m_ret:
                name = m_ret.groups()[0]
                tail = m_ret.groups()[1]
                if name not in self.thrd_libs:
                    self.thrd_libs[name] = {
                        "name" : name,
                        "start": -1,
                        "end": -1,
                    }
                if tail == 'start':
                    self.thrd_libs[name]['start'] = i
                elif tail == 'end':
                    self.thrd_libs[name]['end'] = i
        self.output_path = filepath

    def update(self, name, filepath):
        if name not in self.thrd_libs:
            return
        start_num = self.thrd_libs[name]['start']
        end_num = self.thrd_libs[name]['end']
        print('update lib [%s] between line num %d and % d' % (name, start_num, end_num))
        if end_num > start_num + 1:
            with open_file(filepath, 'r', 'utf-8') as fp:
                content = fp.read()
                fp.close()
                if content[-1] != '\n':
                    content += '\n'
                self.lines[start_num+1] = content
            for num in range(start_num+2, end_num):
                self.lines[num] = ""
        self.has_changed = True

    def save_data_to(self, data, output_path):
        fp = open_file(output_path, 'a+', 'utf-8')
        fp.seek(0)
        fp.truncate()
        fp.write(data)
        fp.flush()
        fp.close()

    def save(self):
        if not self.has_changed:
            print('no lib update,no change')
            return
        data = ''.join(self.lines)
        self.save_data_to(data, self.output_path)

def getJsLibs():
    dirpath = os.path.join(CUR_FILE_DIR, "util")
    retnames = []
    for path, dirnames, filenames in os.walk(dirpath):
        for filename in filenames:
            if filename.endswith('min.js'):
                name = filename.split('.')[0]
                retnames.append(name)
    return retnames

def syncToAll(dirpath):
    handler_list = []
    for path, dirnames, filenames in os.walk(dirpath):
        if path.endswith('util'):
            continue
        for filename in filenames:
            if filename.endswith('.js'):
                filepath = os.path.join(path, filename)
                handler = FileInsertHandler(filepath)
                handler_list.append(handler)
    jslibs = getJsLibs()
    # print(jslibs)
    print('###############start sync###################')
    for handler in handler_list:
        print('filename:' + handler.output_path)
        for jsname in jslibs:
            filename = os.path.join(CUR_FILE_DIR, "util/" + jsname + ".min.js")
            handler.update(jsname, filename)
        handler.save()
        print('\n')

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--dir', help='javascript dir',
                        required=False, default=CUR_FILE_DIR)
    args = parser.parse_args()
    syncToAll(args.dir)

if __name__ == '__main__':
    main()