import os, time
from minio import Minio
# from minio.error import ResponseError
from edge_engine.common.logsetup import logger


class MinioClient:
    def __init__(self ,SECRET_KEY, ACCESS_KEY, BUCKET_NAME, LOCAL_DATA_PATH, MINIO_IP):
        logger.info("Initalizing minioclient !!")
        self.SECRET_KEY = SECRET_KEY
        self.ACCESS_KEY = ACCESS_KEY
        self.BUCKET_NAME = BUCKET_NAME
        self.LOCAL_DATA_PATH = LOCAL_DATA_PATH
        self.MINIO_IP = MINIO_IP
        self.logfile = "./logs/videowrite.log"
        self.minioClient = self.connect_to_minio()
        self.create_bucket(self.BUCKET_NAME)

    def connect_to_minio(self):
            if self.SECRET_KEY is not None and self.ACCESS_KEY is not None:
                logger.info("Connecting to Minio Service... !!! ")
                minio_client = Minio(self.MINIO_IP, access_key = self.ACCESS_KEY, secret_key = self.SECRET_KEY,
                                    region='us-east-1', secure=False)
                return minio_client
            else:
                logger.info('Access Key and Secret Key String cannot be null')
                raise Exception('Access Key and Secret Key String cannot be null')


    def create_bucket(self, bucket_name):
        try:
            if bucket_name not in self.list_buckets():
                logger.info("Creating bucket {}...".format(bucket_name))
                self.minioClient.make_bucket(bucket_name, location="us-east-1")
            else:
                logger.info("Bucket already exists....")
        except Exception as err:
            logger.error(err)

    def save_to_bucket(self, bucket_name, data_obj):
        try:
            with open(data_obj, 'rb') as file:
                file_stat = os.stat(data_obj)
                self.minioClient.put_object(bucket_name, data_obj.split(self.LOCAL_DATA_PATH)[1],
                                       file, file_stat.st_size)
        except Exception as err:
            logger.error(err)

    def list_buckets(self):
        bucketobjects = self.minioClient.list_buckets()
        bucketlist = []
        for eachbucket in bucketobjects:
            bucketlist.append(eachbucket.name)
        return bucketlist

    def read_write_logs(self):
        try:
            f =  open(self.logfile)
        except Exception as err:
            print(err)
            with open(self.logfile, "a") as startfile:
                startfile.write("")
            f = open(self.logfile)
        return [line.split('\n')[0] for line in f]

    def write_write_logs(self, log_str):
        with open(self.logfile, "a") as my_file:
            my_file.write(log_str + "\n")

    def upload(self):
        if self.LOCAL_DATA_PATH[-1]!='/':
            self.LOCAL_DATA_PATH = self.LOCAL_DATA_PATH+"/"
        while True:
            listoffiles = [os.path.join(path, name) for path, subdirs, files in os.walk(self.LOCAL_DATA_PATH) for name in files]
            listofwrittenfiles = self.read_write_logs()
            listofnewfiles = list(set(listoffiles) - set(listofwrittenfiles))
            for fileName in listofnewfiles:
                try:
                    logger.info("Uploading {}..".format(fileName.split(self.LOCAL_DATA_PATH)[1]))
                    self.save_to_bucket(self.BUCKET_NAME, fileName)
                    self.write_write_logs(fileName)
                except Exception as e:
                    logger.error(e)
            time.sleep(5)

# if __name__=='__main__':
#     SECRET_KEY = 'minioadmin'
#     ACCESS_KEY = 'minioadmin'
#     BUCKET_NAME = 'videobucket'
#     MINIO_IP = '192.168.3.220:29000'
#     LOCAL_DATA_PATH = "F:/GDrive Data/Downloads"
#     obj = MinioClient(SECRET_KEY, ACCESS_KEY, BUCKET_NAME, LOCAL_DATA_PATH, MINIO_IP)
#     obj.upload()