import datetime
import shutil


class Generate_link():
    def __init__(self):

        curr_time = datetime.datetime.now()
        self.time_str = curr_time.strftime("%Y-%m-%d")
    def get_info(self, lnk_filename, output):
        vector_count = 1
        d_count = 0
        LEA_flag = 0
        RAM_length2 = 0
        device = self.get_device(lnk_filename)
        flash_data = self.getAddrLenInFile(lnk_filename, "FLASH")
        ram_data = self.getAddrLenInFile(lnk_filename, "SRAM")
        RAM_length = int(ram_data[1], 16) - 0x1500
        # print('%#x'%RAM_length)
        appl2_Flash_start_addr = int((int(flash_data[1], 16) - 0x4000)/2) + 0x4000
        appl_Flash_len = int((int(flash_data[1], 16) - 0x4000)/2)
        Flash_END = int(flash_data[0], 16) + int(flash_data[1], 16)
        # print('%#x'%appl2_Flash_start_addr)
        # print('%#x'%appl_Flash_len)

        filename_OutApp1CCS = output+'/'+device + "_App1.cmd"
        filename_OutApp2CCS = output+'/'+device + "_App2.cmd"
        filename_device_h = output+'/'+"device.h"

        shutil.copyfile('Linker_template/template_App_CCS.tmpl', filename_OutApp1CCS)
        shutil.copyfile('Linker_template/template_App_CCS.tmpl', filename_OutApp2CCS)
        shutil.copyfile('Linker_template/template_device_header.tmpl', filename_device_h)
        # shutil.copyfile(lnk_filename + '.cmd', filename_OutAppCCS)

        ##### Replace text in App1 CCS file#######################################################################################################
        self.replacetextinFile(filename_OutApp1CCS, '<DATE>', self.time_str)
        self.replacetextinFile(filename_OutApp1CCS, '<DEVICE>', device)
        self.replacetextinFile(filename_OutApp1CCS, '<FLASH_START>', '0x4000')
        self.replacetextinFile(filename_OutApp1CCS, '<FLASH_LEN>', str(hex(appl_Flash_len)))
        self.replacetextinFile(filename_OutApp1CCS, '<RAM_LEN>', str(hex(RAM_length)))
        ##### Replace text in App2 CCS file###########################################################################################################
        self.replacetextinFile(filename_OutApp2CCS, '<DATE>', self.time_str)
        self.replacetextinFile(filename_OutApp2CCS, '<DEVICE>', device)
        self.replacetextinFile(filename_OutApp2CCS, '<FLASH_START>', str(hex(appl2_Flash_start_addr)))
        self.replacetextinFile(filename_OutApp2CCS, '<FLASH_LEN>', str(hex(appl_Flash_len)))
        self.replacetextinFile(filename_OutApp2CCS, '<RAM_LEN>', str(hex(RAM_length)))

        ##### Replace text in device.h file###############################################################

        self.replacetextinFile(filename_device_h, '<APP2_FLASH_START>', str(hex(appl2_Flash_start_addr)))
        self.replacetextinFile(filename_device_h, '<FLASH_END>', str(hex(Flash_END)))

    def get_device(self, link_file):
        line = link_file.replace('.', ' ')
        line = line.replace('/', ' ')
        data_array = line.split()
        return data_array[1]
    def getAddrLenInFile(self, cmd_f, mem_type):
        return_list = []
        with open(cmd_f) as file_object:
            lines = file_object.readlines()
        for line in lines:
            if line.find(mem_type) >= 0 and line.find(": origin ="):
                line = line.replace(',', ' ')
                data_array = line.split()
                return_list.append(data_array[5])
                return_list.append(data_array[8])
                return return_list
        return return_list
    def replacetextinFile(self, file, old_str, new_str):
        file_data = ""
        with open(file, "r") as f:
            for line in f:
                if old_str in line:
                    line = line.replace(old_str, new_str)
                file_data += line
        with open(file, "w") as f:
            f.write(file_data)
