from web3 import Web3
# from flask import Flask, request, jsonify
import pbkdf2
import pyaes
import json
import pbkdf2
import pyaes
import requests
from tqdm import tqdm


w3 = Web3()

def encryptionOfPrivate(privateKey,key):
    try:
        url_string = privateKey
        iv = 77423458040705335549997212640120530171624814583885731800099110782272387303263
        passwordSalt = b"\xd3\x06b\xdf\xdc\xd1u\xd0V\xb2\xd8\xbci\xe9\xc8\r"
        password = str(key)
        keyutf = pbkdf2.PBKDF2(password, passwordSalt).read(32)
        # ciphertext = encrypted url string
        aes = pyaes.AESModeOfOperationCTR(keyutf, pyaes.Counter(iv))
        ciphertext = aes.encrypt(str(url_string))
        return ciphertext
    except:
        print("Somthing went worng")


def walletCreation():
    try:
        acc = w3.eth.account.create() 
        # print(f'private key={acc._private_key.hex()}, account={acc.address}')
        encryptPrivateKey =  encryptionOfPrivate(acc._private_key.hex(),"MyNextFilm")
        return acc.address, encryptPrivateKey
    except Exception as e :
        print(e)




def decryptionOfPrivate(privateKey):
    try:
        key1= "MyNextFilm"
        private_key = convertHexToBinary(privateKey)
        url_string = private_key
        iv = 77423458040705335549997212640120530171624814583885731800099110782272387303263
        passwordSalt = b"\xd3\x06b\xdf\xdc\xd1u\xd0V\xb2\xd8\xbci\xe9\xc8\r"
        password = key1
        keyutf = pbkdf2.PBKDF2(password, passwordSalt).read(32)
        # ciphertext = encrypted url string
        aes = pyaes.AESModeOfOperationCTR(keyutf, pyaes.Counter(iv))
        ciphertext = aes.decrypt(url_string)
        return ciphertext
    except:
        print("Somthing went worng") 

def decryptionOfUrl(hash):
    try:
        key= convertHexToBinary(hash)
        url_string = key
        iv = 77423458040705335549997212640120530171624814583885731800099129467854893567836
        passwordSalt = b"\xd3\x06b\xdf\xdc\xd1u\xd0V\xb2\xd8\xbci\xe9\xc8\r"
        password = "MyNextFilm"
        keyutf = pbkdf2.PBKDF2(password, passwordSalt).read(32)
        # ciphertext = encrypted url string
        aes = pyaes.AESModeOfOperationCTR(keyutf, pyaes.Counter(iv))
        ciphertext = aes.decrypt(url_string)
        stringdata = ciphertext.decode('utf-8')
        video_url = f"http://115.245.192.138/Pitchdeck/download_Files/{stringdata}"
        return video_url
    except:
        return "https://mynextfilm.ai/Pitchdeck/download_Files/QmZKWBEKQ28UixqGec6Qz9fEPsJktarzC8NSoFjJ1bgUQo/worng.jpg"
    

def viewDecryptionOfUrl(hash):
    try:
        key= convertHexToBinary(hash)
        url_string = key
        iv = 77423458040705335549997212640120530171624814583885731800099129467854893567836
        passwordSalt = b"\xd3\x06b\xdf\xdc\xd1u\xd0V\xb2\xd8\xbci\xe9\xc8\r"
        password = "MyNextFilm"
        keyutf = pbkdf2.PBKDF2(password, passwordSalt).read(32)
        # ciphertext = encrypted url string
        aes = pyaes.AESModeOfOperationCTR(keyutf, pyaes.Counter(iv))
        ciphertext = aes.decrypt(url_string)
        stringdata = ciphertext.decode('utf-8')
        video_url = f"http://115.245.192.138/ipfs/{stringdata}"
        print(":::::::::::::::::::::",video_url)
        return video_url
    except:
        return "https://mynextfilm.ai/Pitchdeck/view_Files/QmZKWBEKQ28UixqGec6Qz9fEPsJktarzC8NSoFjJ1bgUQo"
    
def decryptionOflocalUrl(hash):
    try:
        key= convertHexToBinary(hash)
        url_string = key
        iv = 77423458040705335549997212640120530171624814583885731800099129467854893567836
        passwordSalt = b"\xd3\x06b\xdf\xdc\xd1u\xd0V\xb2\xd8\xbci\xe9\xc8\r"
        password = "MyNextFilm"
        keyutf = pbkdf2.PBKDF2(password, passwordSalt).read(32)
        # ciphertext = encrypted url string
        aes = pyaes.AESModeOfOperationCTR(keyutf, pyaes.Counter(iv))
        ciphertext = aes.decrypt(url_string)
        stringdata = ciphertext.decode('utf-8')
        video_url = f"http://127.0.0.1:8000/ipfs/{stringdata}"
        print(":::::::::::::::::::::",video_url)
        return video_url
    except:
        return "http://127.0.0.1:8000/ipfs//QmZKWBEKQ28UixqGec6Qz9fEPsJktarzC8NSoFjJ1bgUQo"
def convertHexToBinary(binary):
    hextobainary = bytes.fromhex(binary)
    return hextobainary


def download_file_System(hash,path):
    try:
        _url = decryptionOflocalUrl(hash)
        response11 = requests.get(_url, stream=True)
        # Check if the request was successful
        if response11.status_code == 200:
            # Get the total size of the video in bytes
            total_size = int(response11.headers.get('content-length', 0))
            output_file_path = path
            with open(output_file_path, 'wb') as video_file, tqdm(
                desc=output_file_path,
                total=total_size,
                unit='B',
                unit_scale=True,
                unit_divisor=1024,
            ) as progress_bar:
                for data in response11.iter_content(chunk_size=1024):
                    video_file.write(data)
                    progress_bar.update(len(data))
            print("Video saved successfully.")
            return True
        else:
            print("Failed to download the video. Status code:", response11.status_code)
            return False
    except:
        print("File Is Not Yet....")
        
def hash_decrypation(hash):
    try:
        key= convertHexToBinary(hash)
        url_string = key
        iv = 77423458040705335549997212640120530171624814583885731800099129467854893567836
        passwordSalt = b"\xd3\x06b\xdf\xdc\xd1u\xd0V\xb2\xd8\xbci\xe9\xc8\r"
        password = "MyNextFilm"
        keyutf = pbkdf2.PBKDF2(password, passwordSalt).read(32)
        # ciphertext = encrypted url string
        aes = pyaes.AESModeOfOperationCTR(keyutf, pyaes.Counter(iv))
        ciphertext = aes.decrypt(url_string)
        stringdata = ciphertext.decode('utf-8')
        return stringdata
    except:
        print("something went worng")