import uuid
from typing import Dict, Any
import os
import shutil
from enum import Enum
# from pyspark.sql import SparkSession

# from config import Config as cfg
from app.main.engine.enum.StatusEnum import StatusEnum
from app.main.engine.enum.DescResponseEnum import DescResponseEnum


class Utils:

    def __init__(self, app) -> None:
        self.app = app

    # def createSession(self, name: str = "app_engine_spark") -> SparkSession:
    #     session = None
    #     try:
    #         spark_master = "local["+str(cfg.spark_cores)+"]"
    #         total_mem = cfg.spark_mem
    #         driver_mem = str(int(total_mem / 2)) + 'g'
    #         executor_mem = str(int(total_mem / 2)) + 'g'
    #         jars = list(cfg.spark_jars.values())
    #         jars = ",".join(jars)
    #         session = SparkSession.builder.master(spark_master) \
    #             .appName(name) \
    #             .config("spark.jars", jars) \
    #             .config("spark.executor.extraClassPath", jars) \
    #             .config("spark.driver.extraClassPath", jars) \
    #             .config("spark.driver.memory", driver_mem) \
    #             .config("spark.executor.memory", executor_mem) \
    #             .getOrCreate()
    #
    #     except Exception as e:
    #         self.app.logger.error(f"Error creando sesion Spark. {e}")
    #     finally:
    #         return session

    def create_temp_file(self) -> str:
        fullpath = None
        try:
            dir_name = str(uuid.uuid4())
            path_dir = "/tmp/" + dir_name
            os.mkdir(path_dir)
            filename = str(uuid.uuid4()) + ".csv"
            fullpath = path_dir + "/" + filename
            open(fullpath, mode='a').close()
        except Exception as e:
            self.app.logger.error(f"Error creando directorio temporal.{e}")
        finally:
            return fullpath

    def delete_temp_dir(self, module_name: str) -> bool:
        drop = False
        try:
            if os.path.exists(module_name):
                directory = os.path.dirname(module_name)
                shutil.rmtree(directory, ignore_errors=True)
                self.app.logger.debug(f"directorio borrado: {module_name}")
        except Exception as e:
            raise AssertionError(f"Error borrando modulo temporal. {e}")
        finally:
            return drop

    def create_response(self, codeEnum: Enum, detail: str = "") -> Dict[str, Any]:
        response = {"statusCode": codeEnum.value}

        if codeEnum.value == StatusEnum.SUCCESS.value:
            response.update({'status': StatusEnum.SUCCESS.name.lower(), 'path': detail})
        else:
            description = DescResponseEnum[codeEnum.name].value
            response.update({'status': StatusEnum.ERROR.name.lower(), 'message': description,
                             'detail': detail})
        return response

    def get_script_module(self, action_module: str) -> Dict[str, Any]:
        response = {}
        try:
            pass
        except Exception as e:
            self.app.logger.error(f"Error obteniendo el script del proveedor desde S3. {e}")
            response["status"] = StatusEnum.ERROR
            response["message"] = str(e)
        finally:
            return response

