import os.path

from scripts.task import Task
from utils import SystemUtils, CommandUtils, TimeUtils, FileUtils
from utils.logger_utils import app_logger


def find_path(dir_path: str, suffix: str) -> str:
    l = list(filter(lambda x: x.endswith(suffix), os.listdir(dir_path)))
    if not l:
        raise FileNotFoundError("No such file or directory")
    return os.path.join(dir_path, l[0])


class ProjectBuild(Task):
    """
    assembleLawnWithQuickstepPlay
    bundleLawnWithQuickstepPlayRelease
    """

    def gradlew(self):
        gradlew = os.path.abspath(os.path.join(self.context.temp_project_path, "gradlew"))
        if SystemUtils.is_windows():
            gradlew += ".bat"
        return gradlew

    def build_apk(self):
        cmd = f"{self.gradlew()} -p {self.context.temp_project_path} assembleLawnWithQuickstepPlay"
        app_logger().debug(f"build apk cmd = {cmd}")
        return_code, stdout, stderr = CommandUtils.execute(cmd)
        app_logger().debug(f"build apk return_code = {return_code} stdout = {stdout} stderr = {stderr}")

    def build_aab(self):
        cmd = f"{self.gradlew()} -p {self.context.temp_project_path} bundleLawnWithQuickstepPlayRelease"
        app_logger().debug(f"build aab cmd = {cmd}")
        return_code, stdout, stderr = CommandUtils.execute(cmd)
        app_logger().debug(f"build aab return_code = {return_code} stdout = {stdout} stderr = {stderr}")

    def execute(self):
        self.init()
        self.save_project()
        self.build_apk()
        self.build_aab()
        self.copy_to_out()
        pass

    def init(self):
        file_name = f"{self.context.get_app_name()}_{self.context.package_name}_{self.context.version_display_name}({self.context.version_code})_{self.context.local_repo_branch}({self.context.local_repo_commit[:5]})_{TimeUtils.get_current_time_str()}"
        self.context.out_project = os.path.join("out", f"{file_name}.zip")
        self.context.out_debug_apk = os.path.join("out", f"{file_name}_debug.apk")
        self.context.out_release_apk = os.path.join("out", f"{file_name}_release.apk")
        self.context.out_release_aab = os.path.join("out", f"{file_name}_release.aab")
        pass

    def copy_to_out(self):
        app_logger().debug(f"copy_to_out start.")
        target = f"{self.context.temp_project_path}{os.sep}build{os.sep}outputs{os.sep}apk{os.sep}lawnWithQuickstepPlay{os.sep}debug"
        FileUtils.copy(find_path(target, "apk"), self.context.out_debug_apk)
        app_logger().debug(f"copy_to_out debug apk = {self.context.out_debug_apk}")
        target = f"{self.context.temp_project_path}{os.sep}build{os.sep}outputs{os.sep}apk{os.sep}lawnWithQuickstepPlay{os.sep}release"
        FileUtils.copy(find_path(target, "apk"), self.context.out_release_apk)
        app_logger().debug(f"copy_to_out release apk = {self.context.out_release_apk}")
        target = f"{self.context.temp_project_path}{os.sep}build{os.sep}outputs{os.sep}bundle{os.sep}lawnWithQuickstepPlayRelease"
        FileUtils.copy(find_path(target, "aab"), self.context.out_release_aab)
        app_logger().debug(f"copy_to_out end.")
        pass

    def save_project(self):
        app_logger().debug(f"save project {self.context.out_project} start.")
        FileUtils.compress(self.context.temp_project_path, self.context.out_project)
        app_logger().debug(f"save project {self.context.out_project} end.")
