# mbed SDK
# Copyright (c) 2011-2016 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function, absolute_import
from builtins import str


from os.path import join, exists, realpath, relpath, basename, isfile, splitext
from os import makedirs, listdir, remove, rmdir
import json

from tools.export.makefile import Makefile, GccArm, Armc5, IAR

class VSCode(Makefile):
    """Generic VSCode project. Intended to be subclassed by classes that
    specify a type of Makefile.
    """
    def generate(self):
        """Generate Makefile and VSCode launch and task files
        """
        super(VSCode, self).generate()
        ctx = {
            'name': self.project_name,
            'elf_location': join('BUILD', self.project_name)+'.elf',
            'c_symbols': self.toolchain.get_symbols(),
            'asm_symbols': self.toolchain.get_symbols(True),
            'target': self.target,
            'include_paths': self.resources.inc_dirs,
            'load_exe': str(self.LOAD_EXE).lower()
        }

        if not exists(join(self.export_dir, '.vscode')):
            makedirs(join(self.export_dir, '.vscode'))

        config_files = ['launch', 'settings', 'tasks']
        for file in config_files:
            if not exists('.vscode/%s.json' % file):
                self.gen_file('vscode/%s.tmpl' % file, ctx,
                              '.vscode/%s.json' % file)
            else:
                print('Keeping existing %s.json' % file)

        # So.... I want all .h and .hpp files in self.resources.inc_dirs
        all_directories = []

        for directory in self.resources.inc_dirs:
            if not directory:
                continue

            if directory == ".":
                all_directories.append("${workspaceFolder}/*")
            else:
                all_directories.append(directory.replace("./", "${workspaceFolder}/") + "/*")

        cpp_props = {
            "configurations": [
                {
                    "name": "Windows",
                    "forcedInclude": [
                        "${workspaceFolder}/mbed_config.h"
                    ],
                    "compilerPath": self.toolchain.cppc[0],
                    "intelliSenseMode": "gcc-x64",
                    "includePath": all_directories,
                    "defines": [symbol for symbol in self.toolchain.get_symbols()]
                },
                {
                    "name": "Mac",
                    "forcedInclude": [
                        "${workspaceFolder}/mbed_config.h"
                    ],
                    "compilerPath": self.toolchain.cppc[0],
                    "includePath": all_directories,
                    "defines": [symbol for symbol in self.toolchain.get_symbols()]
                },
                {
                    "name": "Linux",
                    "forcedInclude": [
                        "${workspaceFolder}/mbed_config.h"
                    ],
                    "compilerPath": self.toolchain.cppc[0],
                    "includePath": all_directories,
                    "defines": [symbol for symbol in self.toolchain.get_symbols()]
                }
            ]
        }

        with open(join(self.export_dir, '.vscode', 'c_cpp_properties.json'), 'w') as outfile:
            json.dump(cpp_props, outfile, indent=4, separators=(',', ': '))

    @staticmethod
    def clean(_):
        for f in ['launch', 'settings', 'tasts', 'c_cpp_properties']:
            remove(".vscode/%s.json" % f)
        rmdir(".vscode")

class VSCodeGcc(VSCode, GccArm):
    LOAD_EXE = True
    NAME = "VSCode-GCC-ARM"

class VSCodeArmc5(VSCode, Armc5):
    LOAD_EXE = True
    NAME = "VSCode-Armc5"

class VSCodeIAR(VSCode, IAR):
    LOAD_EXE = True
    NAME = "VSCode-IAR"



@@ -1152,845 +1152,8 @@
 te()
-%0A        ctx = %7B%0A            'name': self.project_name,%0A            'elf_location': join('BUILD', self.project_name)+'.elf',%0A            'c_symbols': self.toolchain.get_symbols(),%0A            'asm_symbols': self.toolchain.get_symbols(True),%0A            'target': self.target,%0A            'include_paths': self.resources.inc_dirs,%0A            'load_exe': str(self.LOAD_EXE).lower()%0A        %7D%0A%0A        if not exists(join(self.export_dir, '.vscode')):%0A            makedirs(join(self.export_dir, '.vscode'))%0A%0A        config_files = %5B'launch', 'settings', 'tasks'%5D%0A        for file in config_files:%0A            if not exists('.vscode/%25s.json' %25 file):%0A                self.gen_file('vscode/%25s.tmpl' %25 file, ctx,%0A                              '.vscode/%25s.json' %25 file)%0A            else:%0A                print('Keeping existing %25s.json' %25 file)
 %0A%0A  
@@ -2879,105 +2879,405 @@
     
-with open(join(self.export_dir, '.vscode', 'c_cpp_properties.json'), 'w') as outfile:%0A           
+ctx = %7B%0A            'name': self.project_name,%0A            'elf_location': join('BUILD', self.project_name)+'.elf',%0A            'c_symbols': self.toolchain.get_symbols(),%0A            'asm_symbols': self.toolchain.get_symbols(True),%0A            'target': self.target,%0A            'include_paths': self.resources.inc_dirs,%0A            'load_exe': str(self.LOAD_EXE).lower(),%0A            'cpp_props':
  jso
@@ -3282,16 +3282,17 @@
 son.dump
+s
 (cpp_pro
@@ -3299,49 +3299,517 @@
 ps, 
-outfile, indent=4
+indent=4, separators=(',', ': '))%0A        %7D%0A%0A        if not exists(join(self.export_dir, '.vscode')):%0A            makedirs(join(self.export_dir, '.vscode'))%0A%0A        config_files = %5B'launch'
 , 
+'
 se
-parators=(',', ': ')
+ttings', 'tasks', 'c_cpp_properties'%5D%0A        for file in config_files:%0A            if not exists('.vscode/%25s.json' %25 file):%0A                self.gen_file('vscode/%25s.tmpl' %25 file, ctx,%0A                              '.vscode/%25s.json' %25 file)%0A            else:%0A                print('Keeping existing %25s.json' %25 file
 )%0A%0A 
@@ -4186,32 +4186,32 @@
 LOAD_EXE = True%0A
+
     NAME = %22VSCo
@@ -4218,10 +4218,8 @@
 de-IAR%22%0A
-%0A%0A

Add c_cpp_properties file to gen_files for zipping