#! /usr/bin/python
# -*- coding: UTF-8 -*-

# coding: utf-8

import os,sys
import random
import string
import re
import time
import json
import shutil
import hashlib
import time
import argparse

import sys

script_path = os.path.split(os.path.realpath(sys.argv[0]))[0]
currentSdkpath = script_path + '/currentSdk'
sdkpath = script_path + '/sdk'


ignore_path_text = [".a", ".storyboard", ".py",".framework",".DS_Store",".xcuserstate",".jpg",".png"]

keyFile = 'zooKeys.json'




def replaceJarNameInFile(full_path, new_text, old_text):
    with open(full_path, "r") as fileObj:
        all_text = fileObj.read()
        fileObj.close()
    if old_text:
        all_text = all_text.replace(old_text, new_text)
        print ("\t替换: %s -> %s" % (old_text, new_text))
        with open(full_path, "w") as fileObj:
            fileObj.write(all_text)
            fileObj.close()
    else:
        print ('cant not find old text')



def getoldJarDate(full_path):
    with open(full_path, "r") as fileObj:
        all_text = fileObj.read()
        fileObj.close()
        # 提取jar包日期
    old_text = (re.findall(r'jm_sdk_([^.jar]+)', all_text)[0])
    return old_text

def main():
    global  sdkpath
    global  currentSdkpath
    print ('start replace jar ...')
    print (sdkpath)
    jarName = ''
    for parent, folders, files in os.walk(currentSdkpath):
        for file in files:
            if file.find(".jar") > -1:
                jarName = file
                print('jarName -->'+ jarName)
    fullJarPath = os.path.join(currentSdkpath,jarName)
    newDate = (re.findall(r'jm_sdk_([^.jar]+)', jarName)[0])

    #修改config字段 及替换Jar包
    list = os.listdir(sdkpath)
    for l in list:
        full_l_path = os.path.join(sdkpath,l)
        full_lib_path = os.path.join(full_l_path,'libs')
        if os.path.isdir(full_l_path):
            configPath = os.path.join(full_l_path,'libs/config.json')
            configPath = os.path.normcase(configPath)
            if os.path.exists(configPath):
                print(configPath)
                oldDate = getoldJarDate(configPath)
                # 修改config字段
                replaceJarNameInFile(configPath,newDate,oldDate)
                oldJarPath = '%s/jm_sdk_%s.jar' % (full_lib_path,oldDate)
                #删除旧文件
                if os.path.exists(oldJarPath):
                    print ('delete ---> %s' % oldJarPath)
                    try:
                        os.remove(os.path.normcase(oldJarPath))
                    except Exception as e:
                        print (e)
                    else:
                        print("File is deleted successfully")
                newJarPath = '%s/jm_sdk_%s.jar' % (full_lib_path,newDate)
                print('复制： %s ---> %s' % (fullJarPath,newJarPath))
                shutil.copyfile(fullJarPath, newJarPath)  # 复制文件

                print('-------------------------')

    print ("\nfinished")

if __name__ == "__main__":
    main()
