import boto3, os, webbrowser,pdfkit, logging, sys, json
from pathlib import Path
import configparser
from botocore.exceptions import ClientError

BASE_DIR = Path(__file__).resolve().parent.parent.parent
config = configparser.ConfigParser()
config.read(os.path.join(BASE_DIR, 'prod.env'))
#print( config.get('linode','key'))
linode_obj_config = {
    "aws_access_key_id": config.get('linode','key'),
    "aws_secret_access_key": config.get('linode','secret'),
    "endpoint_url": config.get('linode','endpoint_url'),
}

client = boto3.client("s3", **linode_obj_config)

#response = client.list_buckets()
# for bucket in response['Buckets']:
#     print(bucket['Name'])
# response = client.list_objects(Bucket='example-bucket', Prefix='assets/')
# for object in response['Contents']:
#     print(object['Key'])
# client.upload_file(
#     Filename='/path/to/file.ext',
#     Bucket='bucket-label',
#     Key='object-name')
# client.upload_file(Filename='/Users/user/logo.jpg', Bucket='example-bucket', Key='images/logo.jpg')
#client.download_file(    Bucket='nc-videos',     Key='route_issue.PNG',    Filename='linodeimg.PNG')    
def object_upload(str_file ='', str_key='',  str_ACK  ='private'):
    #print(str_file, str_key, str_ACK)
    try:
        if str_file is not None and str_file !='' : client.upload_file(Filename=str_file, Bucket=config.get('linode','bucket'), Key=str_key, ExtraArgs={'ACL': str_ACK})
    except: pass

    
def object_public_link(str_key):
    client.put_object_acl(Bucket=config.get('linode','bucket'), Key= str_key,ACL = 'public-read')


def object_upload_public(str_file, str_key):
    if str_key is None:        return 'nouploaded'
    else:
        client.upload_file(Filename=str_file, Bucket=config.get('linode','bucket'), Key=str_key, ExtraArgs={'ACL': 'public-read'})
        str_url = config.get('linode','bucket_url')+'/' +str_key
        #print(str_url)
        webbrowser.open(str_url)
#client.upload_file(Filename='upi_img.jpg', Bucket='nc-videos', Key='docs/upi2.jpg', ExtraArgs={'ACL': 'private'})
#object_upload('upi_img.jpg','public/upi3.jpg')
def PDF_maker(str_url, str_file):
    print( str_file +'.pdf')
    config = pdfkit.configuration(wkhtmltopdf=r"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe")
   # print(BASE_DIR)
    pdfkit.from_url(str_url, os.path.join(BASE_DIR, str_file +'.pdf'), configuration=config)
    webbrowser.open( os.path.join(BASE_DIR, str_file +'.pdf'))

    #object_upload_public(str_file, 'public/Invoice' + os.path.join(BASE_DIR, str_file +'.pdf'))
def singed_url(str_key,expiration=3600):
    #ExpiresIn (int) – The number of seconds the presigned url is valid for. By default it expires in an hour (3600 seconds)
    try:
        response = client.generate_presigned_url('get_object',
                                                    Params={'Bucket': config.get('linode','bucket'),
                                                            'Key': str_key},ExpiresIn=expiration)
    except ClientError as e:
        logging.error(e)
        return None
    return response
#PDF_maker('http://localhost:8080/invoice/view/8/','8')
#PDF_maker('https://google.co.in','8')
#print(singed_url('public/upi.jpg'))
def upload_files(local_path, s3_parent_path, str_ACL = 'private'):
    for path, dirs, files in os.walk(local_path):
        for file in files:
            str_s3folder = str(Path(path).resolve()).replace(str(Path(path).resolve().parent) + '\\','')
            file_s3 = s3_parent_path + str_s3folder + '/' + file
            file_local = os.path.join(path, file)
            #print("Upload:", file_local, "to target:", file_s3, end="")
            client.upload_file(Filename=file_local, Bucket=config.get('linode','bucket'), Key=file_s3, ExtraArgs={'ACL': str_ACL})

def upload_folders_files(local_path, local_path_2, s3_parent_path, str_ACL = 'private'):
    #for path, dirs, files in os.listdir(local_path):
        for file in os.listdir(local_path):
            # replace the additonal para
            str_s3folder = str(os.path.join(local_path, file)).replace(local_path_2 ,'').replace('\\' ,'/')
            if file in str_s3folder:  
                file_s3 = s3_parent_path  + str_s3folder
            else:
                file_s3 = s3_parent_path + str_s3folder + '/' + file
            file_local = os.path.join(local_path, file)
            if os.path.isfile(file_local):        
                client.upload_file(Filename=file_local, Bucket=config.get('linode','bucket'), Key=file_s3, ExtraArgs={'ACL': str_ACL})            
            else:                                 
                upload_folders_files(file_local, local_path_2, s3_parent_path, str_ACL) 
            #print(" ...Success")
#upload_files(r'E:\download\LMS\Lesson')
def list_of_folders(s3_parent_path):
    result = client.list_objects(Bucket=config.get('linode','bucket'), Prefix=s3_parent_path, Delimiter='/')
    #print(result.get('CommonPrefixes')) # total sub folders/objects
    for files in result.get('CommonPrefixes'):
        print(str(files.get('Prefix')).replace(s3_parent_path,'').replace('/',''))

                

def list_of_files_ACL_sub(s3_sub_path, str_ACL):
       # print('sub folder: ' + s3_sub_path)
        list_of_files_ACL3(s3_sub_path, str_ACL)  # in case of sub folders
        for file in client.list_objects(Bucket=config.get('linode','bucket'), Prefix=s3_sub_path, Delimiter='/').get('Contents', []):
            str_key = file.get('Key')  # sub folder - if input is ends with /
            if '.' in str_key.split('/')[len(str_key.split('/'))-1]: #files in same folder
                client.put_object_acl(Bucket=config.get('linode','bucket'), Key=str_key,ACL = str_ACL)
                print('key: ' + str_key)
               # return 'success'
            elif str_key == s3_sub_path and str_key[-1] != '/': print( 'file without extension: ' + str_key)
            elif str_key == s3_sub_path and str_key[-1] == '/': print( 'same folder: ' + str_key)
            else:
                list_of_files_ACL_sub(str_key, str_ACL)
bln_trigger = False
def list_of_files_ACL3(s3_parent_path, str_ACL):
    result = client.list_objects(Bucket=config.get('linode','bucket'), Prefix=s3_parent_path, Delimiter='/')
    global bln_trigger 
    try:
        for folder in result.get('CommonPrefixes'):list_of_files_ACL_sub(folder.get('Prefix'), str_ACL)
            #str_key = folder.get('Prefix') 
            #str_file = str_key.split('/')[len(str_key.split('/'))-2]
            #if  str_file == 'flag-icon-css': bln_trigger = True # to skip up to certain folder
            #if bln_trigger : list_of_files_ACL_sub(folder.get('Prefix'), str_ACL)
            #list_of_files_ACL_sub(folder.get('Prefix'), str_ACL)
            
    except:        return None 

    
def get_numberofitems(s3_parent_path):
    result = client.list_objects(Bucket=config.get('linode','bucket'), Prefix=s3_parent_path, Delimiter='/')
    return len(result.get('CommonPrefixes')) # total sub folders/objects
#print(get_numberofitems('public/cdn1/LMS/Lesson/'))
#upload_files(r'E:\download\LMS\Lesson', 'public/cdn1/LMS/Lesson/')
#upload_files(r'E:\download\LMS\course', 'public/cdn1/LMS/course/')
#list_of_folders('public/cdn1/LMS/Lesson/')
# list_of_files_public('public/cdn1/LMS/Lesson/', 'private')
# list_of_files_public('public/cdn1/LMS/course/', 'public-read')
#upload_files(r'E:\download\CDN\static\lms', 'public/cdn1/CDN/static/lms/')
#upload_files(r'E:\download\CDN\static\bootstrap', 'public/cdn1/CDN/static/bootstrap/')
#list_of_files_ACL('public/cdn1/CDN/static/lms/', 'public-read')
#list_of_files_ACL('public/cdn1/CDN/static/bootstrap/', 'public-read')
#upload_files(r'E:\download\CDN\py', 'public/cdn1/CDN/py/', 'public-read')
#upload_files(r'E:\download\CDN\CUST\nextrevoln', 'public/cdn1/CUST/nextrevoln/', 'public-read')
#list_of_files_ACL3('public/cdn1/Templates/adminlte3/plugins/', 'public-read')


#list_of_files_ACL3('resource/adminlte3/', 'public-read')
#list_of_files_ACL_sub('assets/', 'public-read')
#list_of_files_ACL_sub('prod/', 'public-read')
#list_of_files_ACL_sub('resource/adminlte3/plugins/', 'public-read')

#upload_folders_files(r'E:\download\images\upload', r'E:\download\images\upload', 'public/cdn1/CUST/nextrevoln/Images/Products', 'public-read') 
#upload_folders_files(r'\\server1\profiles\Shares\enghoe\enghoe\static', r'\\server1\profiles\Shares\enghoe\enghoe\static', 'static', 'public-read') 

def list_of_files(s3_parent_path):
    result = client.list_objects(Bucket=config.get('linode','bucket'), Prefix=s3_parent_path, Delimiter='/')
    try:    
        list_files = []     
        for folder in result.get('CommonPrefixes'):    
            str_file = config.get('linode','bucket_url') + folder.get('Prefix')[0:len(folder.get('Prefix'))-1]
            client.put_object_acl(Bucket=config.get('linode','bucket'), Key= folder.get('Prefix'),ACL = 'public-read')
            list_files.append(str_file)
        return list_files
    except:        
        try:
            for folder in result.get('Contents'):    
                str_file = config.get('linode','bucket_url') + folder.get('Key')
                client.put_object_acl(Bucket=config.get('linode','bucket'), Key= folder.get('Key'),ACL = 'public-read')
                list_files.append(str_file)            
            return list_files    
        except:    
            return None 
def list_of_images(str_PID, str_size):
    str_parentpath = 'public/cdn1/CUST/nextrevoln/Images/Products/' +str_PID  + str_size
    return(list_of_files(str_parentpath))

def get_displayimages(str_PID):
    str_PID = str(str_PID)
    json_prod = {"single": list_of_images(str_PID, '/550_380/')}
    json_prod["list"] =   list_of_images(str_PID, '/228_194/')
    json_prod["thumnail"] =   list_of_images(str_PID, '/115_100/')
    print(json.dumps(json_prod))
    return json.dumps(json_prod)
#get_displayimages(55)


#upload_folders_files(r'E:\test\bootstrap5', r'E:\test\bootstrap5', 'public/cdn1/Templates/adminlte3/plugins/bootstrap5', 'public-read') 