import gzip
import os
import os.path as path
import shutil
import tempfile
import boto3
from src.system_var import environment


class S3Client:
    __s3_client = boto3.client('s3')
    _bucket_name: str

    def list_objects(self, bucket_name: str, folder_name: str):
        response = self.__s3_client.list_objects_v2(Bucket=bucket_name, Prefix=folder_name)
        if response['KeyCount'] == 0:
            return []
        contents = response['Contents']
        # 末尾がスラッシュで終わるものはフォルダとみなしてスキップする
        objects = [{'filename': content['Key'], 'size': content['Size']}
                   for content in contents if not content['Key'].endswith('/')]
        return objects

    def copy(self, src_bucket: str, src_key: str, dest_bucket: str, dest_key: str) -> None:
        copy_source = {'Bucket': src_bucket, 'Key': src_key}
        self.__s3_client.copy(copy_source, dest_bucket, dest_key)
        return

    def download_file(self, bucket_name: str, file_key: str, file):
        self.__s3_client.download_fileobj(
            Bucket=bucket_name,
            Key=file_key,
            Fileobj=file
        )
        return

    def upload_file(self, local_file_path: str, bucket_name: str, file_key: str):
        self.__s3_client.upload_file(
            local_file_path,
            Bucket=bucket_name,
            Key=file_key
        )

    def delete_file(self, bucket_name: str, file_key: str):
        self.__s3_client.delete_object(
            Bucket=bucket_name,
            Key=file_key
        )

class S3Bucket():
    _s3_client = S3Client()
    _bucket_name: str = None

class  JskultArchiveBucket(S3Bucket):
    _bucket_name = environment.JSKULT_ARCHIVE_BUCKET

    def upload_archive_zip_file(self, archive_zip: str, archive_zip_path: str, send_folder: str):
        # S3バケットにファイルを移動
        archive_zip_name = f'{send_folder}/{archive_zip}'
        s3_client = S3Client()
        s3_client.upload_file(archive_zip_path, self._bucket_name, archive_zip_name)
        return f"{self._bucket_name}/{archive_zip_name}"