import requests
import time
from tqdm import tqdm
import ast
import json
from WalletCreation import walletCreation
# from users.models import UserCredentialsForBlockchain
from pymongo import MongoClient

from blockchainsetting import UPLOAD_FILES,SET_ONLY_OWNER, GET_OWNER




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



# url = "http://127.0.0.1:8005/Write/onlyOwner"
# geturl = "http://127.0.0.1:8005/Fetch/onlyOwner"

# uploadApi = "http://127.0.0.1:5000/upload"

def uploadAfile():
    # file = open('/home/user/mnf/project/MNF/Blockchain2/big_buck_bunny_720p_30mb.mp4', 'r')
    # content = file.read()
    # Replace 'video.mp4' with the path to your video file
    # video_path = '/home/user/mnf/project/MNF/Blockchain2/videoplayback.mp4'

    # Open the video file in binary read mode
    # with open(video_path, 'rb') as video_file:
    #     video_data = video_file.read()
    data ={
        "file":"hello world"
    }
    response =requests.post(UPLOAD_FILES,files=data)
    print(response.json())
    data = response.json()
    print(data["hash"])

# uploadAfile()

def getFileFromIpfs():
    video_url = "http://127.0.0.1:8000/ipfs/QmUEoaJYnNtENrBPq4z9Vb3ZHz9YUNU7hzusPAUgWkKZLE"
    response = requests.get(video_url, stream=True)

    # Check if the request was successful
    if response.status_code == 200:
        # Get the total size of the video in bytes
        total_size = int(response.headers.get('content-length', 0))

        # Replace 'video.mp4' with the desired file path and name
        output_file_path = 'video1.mp4'

        # Save the video to a local file with a progress bar
        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 response.iter_content(chunk_size=1024):
                video_file.write(data)
                progress_bar.update(len(data))
        print("Video saved successfully.")
    else:
        print("Failed to download the video. Status code:", response.status_code)
# getFileFromIpfs()

def postdatas():
    Counter = 0
    startTime= time.time()
    disct = {
    "showcase_id": {
        "$binary": {
        "base64": "grPhbfRRS7mtVQlnUXrFgg==",
        "subType": "03"
        }
    },
    "user_id_id": 1,
    "project_number": Counter,
    "showcase_string": "1670584877.626224-showcase",
    "date_of_submission": {
        "$date": "2022-12-09T11:21:38.738Z"
    },
    "loglines": "xsdcfv",
    "projecttitle": "xdcfvg",
    "projecttype": "",
    "languageactionlines": "Arabic",
    "languagedialogues": "Arabic",
    "genre": "Drama",
    "rating": "0.00",
    "total_rating": 0,
    "viewercount": 0,
    "subgenre": "",
    "shortfilm": "false",
    "documentory": "false",
    "webseries": "false",
    "tvserial": "false",
    "featurefilm": "false",
    "other": "false",
    "other_value": "",
    "setintime": "Medieval",
    "setingeography": "xedcrvt",
    "duration": 123,
    "copyright": "false",
    "registered_with": "",
    "anycoauthor": "false",
    "nameofcoauthor": "",
    "emailidcoauthor": "",
    "budgetcurrency": "CAD",
    "budgetamount": 1234,
    "projectstatus": "Project Completed",
    "noofscenes": "",
    "noofcharacters": "",
    "nooflocations": "",
    "specialrequirement": "",
    "starcast": "",
    "onepageruploaded": {
        "$binary": {
        "base64": "k++jaa8DEFGn6cYMqkSE8yIzNyrFLDF3zRKlIFEi8Y11e0R9imMNJYl9jf7R8A==",
        "subType": "00"
        }
    },
    "storyuploaded": "null",
    "samplescriptuploaded": "null",
    "fullscriptuploaded": "null",
    "samplefootageuploaded": "null",
    "findcowriter": "false",
    "commissionproject": "false",
    "partfinancing": "false",
    "fullfinancing": "false",
    "fundrequiredcurrency": "null",
    "fundrequiredamount": 0,
    "auction_fullrights": "false",
    "auction_limitedrights": "false",
    "auctionstartdate": "null",
    "auctionstopdate": "null",
    "reservepricecurrency": "null",
    "reservepriceamount": 0,
    "pitchdeckuploaded": "null",
    "samplenarrationuploaded": "null",
    "characterintrouploaded": "null",
    "scriptanalysisuploaded": "null",
    "narratefulluploaded": "null",
    "narratefulluploaded_s3": "null",
    "total_file_size": 102572,
    "whocansee_story": "null",
    "whocansee_onepager": "null",
    "whocansee_samplescript": "null",
    "whocansee_samplenarration": "null",
    "whocansee_fullscript": "null",
    "whocansee_fullnarration": "null",
    "whocansee_scriptanalysis": "null",
    "whocansee_charintroduction": "null",
    "whocansee_samplefootage": "null",
    "whocansee_pitchdeck": "null",
    "showcase_shortlist_count": 0,
    "uploaded_at": 1670584877
    }

    payloadStrData = str(disct)
    data ={
    "user_id":1,
    "Module": "narration",
    "Services": "PitchdeckCreation",
    "project":123,
    "Data": "asdf",
    "File":["cid","cid2"],
    "userPrivateKey":"3f14b27e3d2fbb5043c0064a91a6fc05dfcb340a5b74a6afcc42094147255e2cc967889a245d864f36412cb441b83bddf0f4c0976dfcc4245c0b880896e05eb56877"

    }
    
    response =requests.post(SET_ONLY_OWNER,json=data)
    print(response.json())
    Counter+=1
    endTime= time.time()
    finalTime = endTime-startTime
    print(finalTime)

postdatas()  
# 
def getdata():
    Counter=0
    startTime= time.time()
    Module= "narration"
    servicesName = "PitchdeckCreation"
    data ={
    # "private_key":"0x6f06e1108b833b1918067042e13e60eda262705b80385a02d0330ce0db31d3ad",
    "private_key":"3f14b27e3d2fbb5043c0064a91a6fc05dfcb340a5b74a6afcc42094147255e2cc967889a245d864f36412cb441b83bddf0f4c0976dfcc4245c0b880896e05eb56877",
    "user_id": 1,
    "Module": Module,
    "Services": servicesName,
    "Project": 1,
    }
    
    response =requests.get(GET_OWNER,params=data)
    getData = response.json()
    print(">>>>>>>>>>>>>>",getData)

    getdatafromblockchain = getData.get("getData")[2][1]
    print(getdatafromblockchain)
    # print(getdatafromblockchain, type(getdatafromblockchain))
    # finalstring = "[{'onepager': 'True', 'id': 1, 'user_id_id': 'yadavkiran699@gmail.com', 'script_id': 'scr_1690533008', 'script_title': 'Looper_5733_CiQg5Tr', 'actionline_language': 'en', 'actionline_script_language': 'Latin', 'dialogues_language': 'en', 'dialogues_script_language': 'Latin', 'document_name': 'Looper_5733_CiQg5Tr.docx', 'script_file_path': '/home/user/mnf/project/MNF/media/scripts/Looper_5733_CiQg5Tr.docx', 'author_name': 'yadavkiran699@gmail.com'}, {'choosescript': 'Looper_5733_CiQg5Tr.docx', 'scriptDetails': <MNFScriptDatabase: scr_1690533008>, 'scriptname': <FieldFile: None>, 'genre': 'Comedy', 'subGenre': 'Comedic Thriller', 'projecttype': 'Feature Film', 'noepisodes': '', 'eachepisodes': '', 'language': 'Chinese', 'dialect_language': 'Mandarin', 'platformproposed': '', 'country': '', 'countryCode': '+91', 'city': None, 'state': None, 'languagebelt': '', 'target_audience': '', 'target_field': '', 'timeperiod': 'Ancient Times', 'geography': '', 'dialogue_reference': '', 'premise': '', 'logline': 'as sa as as sa saa as sa sa sa', 'author': True, 'name': 'yadavkiran699@gmail.com', 'author_profile': None, 'author_email': 'yadavkiran699@gmail.com', 'phonenumber': '0000000000000', 'author_about': 'as sa as as sa saa as sa sa sa', 'author_link': '', 'auplot_story_flowthor': True, 'protagonist': 'as sa as as sa saa as sa sa sa', 'barrier': 'as sa as as sa saa as sa sa sa', 'midpoint': 'as sa as as sa saa as sa sa sa', 'climax': 'as sa as as sa saa as sa sa sa', 'conflictresolved': 'as sa as as sa saa as sa sa sa', 'minute_protogonist': '0', 'conflict_reaches_climax': '0', 'dream_cast_locations': True, 'upload_image1': None, 'leadcharacter': ['JOE', 'asasasasaa', None], 'strengths_and_expectation': True, 'monetary_non_monetary_expectation': ''}]"
    # print(finalstring)
    # varibale = "{'onepager': 'True', 'id': 1, 'user_id_id': 'yadavkiran699@gmail.com', 'script_id': 'scr_1690533008', 'script_title': 'Looper_5733_CiQg5Tr', 'actionline_language': 'en', 'actionline_script_language': 'Latin', 'dialogues_language': 'en', 'dialogues_script_language': 'Latin', 'document_name': 'Looper_5733_CiQg5Tr.docx', 'script_file_path': '/home/user/mnf/project/MNF/media/scripts/Looper_5733_CiQg5Tr.docx', 'author_name': 'yadavkiran699@gmail.com'}"
    # pravesh = "[{'pravesh': 33},{'pravesh': 33}]"
    # varibale1 = "{'choosescript': 'Looper_5733_CiQg5Tr.docx','scriptDetails': '<MNFScriptDatabase: scr_1690533008>', 'scriptname': '<FieldFile: None>', 'genre': 'Comedy', 'subGenre': 'Comedic Thriller', 'projecttype': 'Feature Film', 'noepisodes': '', 'eachepisodes': '', 'language': 'Chinese', 'dialect_language': 'Mandarin', 'platformproposed': '', 'country': '', 'countryCode': '+91', 'city': 'None', 'state': 'None', 'languagebelt': '', 'target_audience': '', 'target_field': '', 'timeperiod': 'Ancient Times', 'geography': '', 'dialogue_reference': '', 'premise': '', 'logline': 'as sa as as sa saa as sa sa sa', 'author': 'True', 'name': 'yadavkiran699@gmail.com', 'author_profile': 'None', 'author_email': 'yadavkiran699@gmail.com', 'phonenumber': '0000000000000', 'author_about': 'as sa as as sa saa as sa sa sa', 'author_link': '', 'auplot_story_flowthor': 'True', 'protagonist': 'as sa as as sa saa as sa sa sa', 'barrier': 'as sa as as sa saa as sa sa sa', 'midpoint': 'as sa as as sa saa as sa sa sa', 'climax': 'as sa as as sa saa as sa sa sa', 'conflictresolved': 'as sa as as sa saa as sa sa sa', 'minute_protogonist': '0', 'conflict_reaches_climax': '0', 'dream_cast_locations': 'True', 'upload_image1': 'None', 'leadcharacter': ['JOE', 'asasasasaa', 'None'], 'strengths_and_expectation': 'True', 'monetary_non_monetary_expectation': ''}"
    # try:
        
    #     # disct = ast.literal_eval(getdatafromblockchain)
    #     # print(disct)

    #     # converted_dict = eval(getdatafromblockchain)
    #     # print(converted_dict["MNFScriptDatabase1"])
    # except Exception as e:
    #     print(e)
def load_string_to_dicts(data):   
    string_data = data.replace("'", '"')
    list_data = json.loads(string_data)
    return list_data

# getdata()   

            # accountDetail = walletCreation()
            # binaryToHex = accountDetail[1].hex()
            # blockchain_obj = UserCredentialsForBlockchain()
            # blockchain_obj.user = user
            # blockchain_obj.privateKey = binaryToHex
            # blockchain_obj.publicKey = accountDetail[0]
            # blockchain_obj.save()
        # MongoDBUrl = "mongodb+srv://MNF:root@cluster0.gbkxi.gcp.mongodb.net/DB?retryWrites=true&w=majority"
# MongoDBUrl = "mongodb+srv://mynextfilm:mnf123@cluster0.ojasb.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"
# client = MongoClient(MongoDBUrl)
# db = client.DB

# users = db["auth_user"].find()
# for user in users:
#     if "id" in user:
#         print(user["id"])
# accountDetail = walletCreation()
# binaryToHex = accountDetail[1].hex()
# blockchain_obj = UserCredentialsForBlockchain()
# blockchain_obj.user = 1
# blockchain_obj.privateKey = binaryToHex
# blockchain_obj.publicKey = accountDetail[0]
# blockchain_obj.save()