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

#
# Copyright (c) 2023 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 shutil

from containers.arg import Arg
from resolver.interface.args_resolver_interface import ArgsResolverInterface
from modules.interface.clean_module_interface import CleanModuleInterface
from resources.global_var import CURRENT_OHOS_ROOT, DEFAULT_CCACHE_DIR
from resources.config import Config
from util.log_util import LogUtil


class CleanArgsResolver(ArgsResolverInterface):

    def __init__(self, args_dict: dict):
        super().__init__(args_dict)

    @staticmethod
    def resolve_clean_args(target_arg: Arg, clean_module: CleanModuleInterface):
        if target_arg.arg_value or clean_module.args_dict['clean_all'].arg_value:
            LogUtil.hb_info(
                'Clean all args that generated by last compilation')
            Arg.clean_args_file()

    @staticmethod
    def resolve_clean_out_product(target_arg: Arg, clean_module: CleanModuleInterface):
        if target_arg.arg_value or clean_module.args_dict['clean_all'].arg_value:
            config = Config()
            if config.out_path is not None and config.out_path != '' \
                    and config.out_path.startswith(CURRENT_OHOS_ROOT) and os.path.exists(config.out_path):
                LogUtil.hb_info(
                    'Clean {} directory that generated by last compilation'.format(config.out_path))
                shutil.rmtree(config.out_path)

    @staticmethod
    def resolve_clean_ccache(target_arg: Arg, clean_module: CleanModuleInterface):
        if target_arg.arg_value or clean_module.args_dict['clean_all'].arg_value:
            if os.path.exists(DEFAULT_CCACHE_DIR):
                LogUtil.hb_info(
                    'Clean ccache "{}" directory'.format(DEFAULT_CCACHE_DIR))
                shutil.rmtree(DEFAULT_CCACHE_DIR)

    @staticmethod
    def resolve_clean_all(target_arg: Arg, clean_module: CleanModuleInterface):
        if target_arg.arg_value:
            CleanArgsResolver.resolve_clean_out_product(
                target_arg, clean_module)
            CleanArgsResolver.resolve_clean_ccache(target_arg, clean_module)