#######################################################################################
# Copyright ETSI Contributors and Others.
#
# 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 yaml
from osm_lcm.lcm_utils import LcmException


async def create_oka(self, op_id, op_params, content):
    self.logger.info("Create OKA workflow Enter")
    self.logger.info(f"Operation {op_id}. Params: {op_params}. Content: {content}")

    workflow_template = "launcher-create-oka.j2"
    workflow_name = f"create-oka-{content['_id']}"

    # Additional params for the workflow
    oka_name = content["git_name"].lower()
    oka_type = "infra-controllers"
    osm_project_name = "osm_admin"  # TODO: get project name from content

    # Get the OKA package
    oka_fs_info = content["_admin"]["storage"]
    oka_folder = f"{oka_fs_info['path']}{oka_fs_info['folder']}"
    oka_filename = oka_fs_info["zipfile"]
    self.fs.sync(oka_folder)
    if not self.fs.file_exists(f"{oka_folder}/{oka_filename}"):
        raise LcmException(message="Not able to find oka", bad_args=["oka_path"])

    # Create temporary volume for the OKA package and copy the content
    temp_volume_name = f"temp-pvc-oka-{op_id}"
    await self._kubectl.create_pvc_with_content(
        name=temp_volume_name,
        namespace="osm-workflows",
        src_folder=oka_folder,
        filename=oka_filename,
    )

    # Render workflow
    manifest = self.render_jinja_template(
        workflow_template,
        output_file=None,
        workflow_name=workflow_name,
        git_fleet_url=f"{self._repo_base_url}/{self._repo_user}/fleet-osm.git",
        git_sw_catalogs_url=f"{self._repo_base_url}/{self._repo_user}/sw-catalogs-osm.git",
        oka_name=oka_name,
        oka_type=oka_type,
        osm_project_name=osm_project_name,
        temp_volume_name=temp_volume_name,
        workflow_debug=self._workflow_debug,
        workflow_dry_run=self._workflow_dry_run,
    )
    self.logger.info(manifest)

    # Submit workflow
    self._kubectl.create_generic_object(
        namespace="osm-workflows",
        manifest_dict=yaml.safe_load(manifest),
        api_group="argoproj.io",
        api_plural="workflows",
        api_version="v1alpha1",
    )
    return workflow_name


async def update_oka(self, op_id, op_params, content):
    self.logger.info("Update OKA workflow Enter")
    self.logger.info(f"Operation {op_id}. Params: {op_params}. Content: {content}")

    workflow_template = "launcher-update-oka.j2"
    workflow_name = f"update-oka-{content['_id']}"

    # Additional params for the workflow
    oka_name = content["git_name"].lower()
    oka_type = "infra-controllers"
    osm_project_name = "osm_admin"  # TODO: get project name from content

    # Get the OKA package
    oka_fs_info = content["_admin"]["storage"]
    oka_folder = (
        f"{oka_fs_info['path']}/{oka_fs_info['folder']}/{oka_fs_info['zipfile']}"
    )
    oka_filename = "package.tar.gz"
    # Sync fs?

    # Create temporary volume for the OKA package and copy the content
    temp_volume_name = f"temp-pvc-oka-{op_id}"
    await self._kubectl.create_pvc_with_content(
        name=temp_volume_name,
        namespace="osm-workflows",
        src_folder=oka_folder,
        filename=oka_filename,
    )

    # Render workflow
    manifest = self.render_jinja_template(
        workflow_template,
        output_file=None,
        workflow_name=workflow_name,
        git_fleet_url=f"{self._repo_base_url}/{self._repo_user}/fleet-osm.git",
        git_sw_catalogs_url=f"{self._repo_base_url}/{self._repo_user}/sw-catalogs-osm.git",
        oka_name=oka_name,
        oka_type=oka_type,
        osm_project_name=osm_project_name,
        temp_volume_name=temp_volume_name,
        workflow_debug=self._workflow_debug,
        workflow_dry_run=self._workflow_dry_run,
    )
    self.logger.info(manifest)

    # Submit workflow
    self._kubectl.create_generic_object(
        namespace="osm-workflows",
        manifest_dict=yaml.safe_load(manifest),
        api_group="argoproj.io",
        api_plural="workflows",
        api_version="v1alpha1",
    )
    return workflow_name


async def delete_oka(self, op_id, op_params, content):
    self.logger.info("Delete OKA workflow Enter")
    self.logger.info(f"Operation {op_id}. Params: {op_params}. Content: {content}")

    workflow_template = "launcher-delete-oka.j2"
    workflow_name = f"delete-oka-{content['_id']}"

    # Additional params for the workflow
    oka_name = content["git_name"].lower()
    oka_type = "infra-controllers"
    osm_project_name = "osm_admin"  # TODO: get project name from content

    # Render workflow
    manifest = self.render_jinja_template(
        workflow_template,
        output_file=None,
        workflow_name=workflow_name,
        git_fleet_url=f"{self._repo_base_url}/{self._repo_user}/fleet-osm.git",
        git_sw_catalogs_url=f"{self._repo_base_url}/{self._repo_user}/sw-catalogs-osm.git",
        oka_name=oka_name,
        oka_type=oka_type,
        osm_project_name=osm_project_name,
        workflow_debug=self._workflow_debug,
        workflow_dry_run=self._workflow_dry_run,
    )
    self.logger.info(manifest)

    # Submit workflow
    self._kubectl.create_generic_object(
        namespace="osm-workflows",
        manifest_dict=yaml.safe_load(manifest),
        api_group="argoproj.io",
        api_plural="workflows",
        api_version="v1alpha1",
    )
    return workflow_name


async def check_create_oka(self, op_id, op_params, content):
    self.logger.info(f"Operation {op_id}. Params: {op_params}. Content: {content}")
    return True, "OK"


async def check_update_oka(self, op_id, op_params, content):
    self.logger.info(f"Operation {op_id}. Params: {op_params}. Content: {content}")
    return True, "OK"


async def check_delete_oka(self, op_id, op_params, content):
    self.logger.info(f"Operation {op_id}. Params: {op_params}. Content: {content}")
    return True, "OK"
