#!/usr/bin/env python3
# coding=utf-8

#
# Copyright (c) 2021 Huawei Device Co., Ltd.
# 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.
#

import os
import sys
import json
import shutil

from core.constants import JsTestConst
from xdevice import platform_logger

LOG = platform_logger("PretreatTargets")


##############################################################################
##############################################################################

class PretreatTargets(object):
    def __init__(self, target_list):
        self.path_list = []
        self.name_list = []
        self.target_list = target_list

    def pretreat_targets_from_list(self):
        path_list, name_list = self._parse_target_info()
        self._pretreat_by_target_name(path_list, name_list)

    def disassemble_targets_from_list(self):
        self._disassemble_by_target_name(self.path_list, self.name_list)

    def _parse_target_info(self):
        path_list = []
        name_list = []

        for line in self.target_list:
            path = line.split(':')[0][2:]
            name = line.split(':')[1].split('(')[0]
            path_list.append(path)
            name_list.append(name)

        return path_list, name_list

    def _pretreat_by_target_name(self, path_list, name_list):
        for name, path in zip(name_list, path_list):
            if name.endswith("JsTest"):
                if self._pretreat_js_target(path, name):
                    self.path_list.append(path)
                    self.name_list.append(name)
                    LOG.info("js test %s pretreat success" % name)

    def _pretreat_js_target(self, path, name):
        template_path = os.path.join(sys.framework_root_dir, "libs",
                                     "js_template", "src")
        target_path = os.path.join(sys.source_code_root_path, path)
        config_path = os.path.join(target_path, "config.json")
        gn_path = os.path.join(target_path, "BUILD.gn")
        gn_bak_path = os.path.join(target_path, "BuildBak")
        test_path = os.path.join(target_path, "src", "main", "js",
                                 "default", "test")
        if not os.path.exists(config_path):
            LOG.error("js test needs config.json file")
            return False
        if not os.path.exists(gn_path):
            LOG.error("js test needs BUILD.gn file")
            return False
        LOG.info("target_path: %s" % target_path)

        #modify BUILD.gn file to compile hap
        output_path = self._parse_output_path_in_gn(gn_path)
        if output_path == "":
            LOG.error(" BUILD.gn needs 'module_output_path'")
            return
        os.rename(gn_path, gn_bak_path)
        template_args = {'output_path': output_path, 'suite_name': name}
        with open(gn_path, 'w') as filehandle:
            filehandle.write(JsTestConst.BUILD_GN_FILE_TEMPLATE %
                             template_args)

        #copy js hap template to target path
        shutil.copytree(template_path, os.path.join(target_path, "src"))
        shutil.copy(config_path, os.path.join(target_path, "src", "main"))
        file_name = os.listdir(target_path)
        for file in file_name:
            if file.endswith(".js"):
                LOG.info("file: %s" % file)
                shutil.copy(os.path.join(target_path, file), test_path)
                with open(os.path.join(test_path, "List.test.js"), 'a') \
                        as list_data:
                    list_data.write("require('./%s')" % file)

        #modify i18n json file
        i18n_path = os.path.join(target_path, "src", "main", "js",
                                 "default", "i18n", "en-US.json")
        json_data = ""
        with open(i18n_path, 'r') as i18n_file:
            lines = i18n_file.readlines()
            for line in lines:
                if "TargetName" in line:
                    line = line.replace("TargetName", name)
                json_data += line
        with open(i18n_path, 'w') as i18n_file:
            i18n_file.write(json_data)
        return True

    def _parse_output_path_in_gn(self, gn_path):
        output_path = ""
        with open(gn_path, 'r') as gn_file:
            for line in gn_file.readlines():
                if line.startswith("module_output_path"):
                    output_path = line.split()[2].strip('"')
                    break
        return output_path

    def _disassemble_by_target_name(self, path_list, name_list):
        for name, path in zip(name_list, path_list):
            LOG.info("name: %s path: %s" % (name, path))
            if name.endswith("JsTest"):
                self._disassemble_js_target(path, name)
                LOG.info("js test %s disassemble success" % name)

    def _disassemble_js_target(self, path, name):
        target_path = os.path.join(sys.source_code_root_path, path)
        src_path = os.path.join(target_path, "src")
        gn_path = os.path.join(target_path, "BUILD.gn")
        gn_bak_path = os.path.join(target_path, "BuildBak")

        if os.path.exists(src_path):
            shutil.rmtree(src_path)
        if os.path.exists(gn_path) and os.path.exists(gn_bak_path):
            os.remove(gn_path)
            os.rename(gn_bak_path, gn_path)

##############################################################################
##############################################################################

[((27, 6, 27, 40), 'xdevice.platform_logger', 'platform_logger', ({(27, 22, 27, 39): '"""PretreatTargets"""'}, {}), "('PretreatTargets')", False, 'from xdevice import platform_logger\n'), ((67, 24, 68, 58), 'os.path.join', 'os.path.join', ({(67, 37, 67, 59): 'sys.framework_root_dir', (67, 61, 67, 67): '"""libs"""', (68, 37, 68, 50): '"""js_template"""', (68, 52, 68, 57): '"""src"""'}, {}), "(sys.framework_root_dir, 'libs', 'js_template', 'src')", False, 'import os\n'), ((69, 22, 69, 67), 'os.path.join', 'os.path.join', ({(69, 35, 69, 60): 'sys.source_code_root_path', (69, 62, 69, 66): 'path'}, {}), '(sys.source_code_root_path, path)', False, 'import os\n'), ((70, 22, 70, 62), 'os.path.join', 'os.path.join', ({(70, 35, 70, 46): 'target_path', (70, 48, 70, 61): '"""config.json"""'}, {}), "(target_path, 'config.json')", False, 'import os\n'), ((71, 18, 71, 55), 'os.path.join', 'os.path.join', ({(71, 31, 71, 42): 'target_path', (71, 44, 71, 54): '"""BUILD.gn"""'}, {}), "(target_path, 'BUILD.gn')", False, 'import os\n'), ((72, 22, 72, 59), 'os.path.join', 'os.path.join', ({(72, 35, 72, 46): 'target_path', (72, 48, 72, 58): '"""BuildBak"""'}, {}), "(target_path, 'BuildBak')", False, 'import os\n'), ((73, 20, 74, 51), 'os.path.join', 'os.path.join', ({(73, 33, 73, 44): 'target_path', (73, 46, 73, 51): '"""src"""', (73, 53, 73, 59): '"""main"""', (73, 61, 73, 65): '"""js"""', (74, 33, 74, 42): '"""default"""', (74, 44, 74, 50): '"""test"""'}, {}), "(target_path, 'src', 'main', 'js', 'default', 'test')", False, 'import os\n'), ((88, 8, 88, 39), 'os.rename', 'os.rename', ({(88, 18, 88, 25): 'gn_path', (88, 27, 88, 38): 'gn_bak_path'}, {}), '(gn_path, gn_bak_path)', False, 'import os\n'), ((97, 20, 97, 43), 'os.listdir', 'os.listdir', ({(97, 31, 97, 42): 'target_path'}, {}), '(target_path)', False, 'import os\n'), ((107, 20, 108, 65), 'os.path.join', 'os.path.join', ({(107, 33, 107, 44): 'target_path', (107, 46, 107, 51): '"""src"""', (107, 53, 107, 59): '"""main"""', (107, 61, 107, 65): '"""js"""', (108, 33, 108, 42): '"""default"""', (108, 44, 108, 50): '"""i18n"""', (108, 52, 108, 64): '"""en-US.json"""'}, {}), "(target_path, 'src', 'main', 'js', 'default', 'i18n', 'en-US.json')", False, 'import os\n'), ((137, 22, 137, 67), 'os.path.join', 'os.path.join', ({(137, 35, 137, 60): 'sys.source_code_root_path', (137, 62, 137, 66): 'path'}, {}), '(sys.source_code_root_path, path)', False, 'import os\n'), ((138, 19, 138, 51), 'os.path.join', 'os.path.join', ({(138, 32, 138, 43): 'target_path', (138, 45, 138, 50): '"""src"""'}, {}), "(target_path, 'src')", False, 'import os\n'), ((139, 18, 139, 55), 'os.path.join', 'os.path.join', ({(139, 31, 139, 42): 'target_path', (139, 44, 139, 54): '"""BUILD.gn"""'}, {}), "(target_path, 'BUILD.gn')", False, 'import os\n'), ((140, 22, 140, 59), 'os.path.join', 'os.path.join', ({(140, 35, 140, 46): 'target_path', (140, 48, 140, 58): '"""BuildBak"""'}, {}), "(target_path, 'BuildBak')", False, 'import os\n'), ((142, 11, 142, 35), 'os.path.exists', 'os.path.exists', ({(142, 26, 142, 34): 'src_path'}, {}), '(src_path)', False, 'import os\n'), ((75, 15, 75, 42), 'os.path.exists', 'os.path.exists', ({(75, 30, 75, 41): 'config_path'}, {}), '(config_path)', False, 'import os\n'), ((78, 15, 78, 38), 'os.path.exists', 'os.path.exists', ({(78, 30, 78, 37): 'gn_path'}, {}), '(gn_path)', False, 'import os\n'), ((95, 39, 95, 71), 'os.path.join', 'os.path.join', ({(95, 52, 95, 63): 'target_path', (95, 65, 95, 70): '"""src"""'}, {}), "(target_path, 'src')", False, 'import os\n'), ((96, 33, 96, 73), 'os.path.join', 'os.path.join', ({(96, 46, 96, 57): 'target_path', (96, 59, 96, 64): '"""src"""', (96, 66, 96, 72): '"""main"""'}, {}), "(target_path, 'src', 'main')", False, 'import os\n'), ((143, 12, 143, 35), 'shutil.rmtree', 'shutil.rmtree', ({(143, 26, 143, 34): 'src_path'}, {}), '(src_path)', False, 'import shutil\n'), ((144, 11, 144, 34), 'os.path.exists', 'os.path.exists', ({(144, 26, 144, 33): 'gn_path'}, {}), '(gn_path)', False, 'import os\n'), ((144, 39, 144, 66), 'os.path.exists', 'os.path.exists', ({(144, 54, 144, 65): 'gn_bak_path'}, {}), '(gn_bak_path)', False, 'import os\n'), ((145, 12, 145, 30), 'os.remove', 'os.remove', ({(145, 22, 145, 29): 'gn_path'}, {}), '(gn_path)', False, 'import os\n'), ((146, 12, 146, 43), 'os.rename', 'os.rename', ({(146, 22, 146, 33): 'gn_bak_path', (146, 35, 146, 42): 'gn_path'}, {}), '(gn_bak_path, gn_path)', False, 'import os\n'), ((101, 28, 101, 59), 'os.path.join', 'os.path.join', ({(101, 41, 101, 52): 'target_path', (101, 54, 101, 58): 'file'}, {}), '(target_path, file)', False, 'import os\n'), ((102, 26, 102, 65), 'os.path.join', 'os.path.join', ({(102, 39, 102, 48): 'test_path', (102, 50, 102, 64): '"""List.test.js"""'}, {}), "(test_path, 'List.test.js')", False, 'import os\n')]