import pymysql
import json
from flask import Flask, Response,request
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Util.Padding import pad
from Crypto.Util.Padding import unpad
import base64


app = Flask(__name__)
c_flag = 'https://vpnforchrome.vpnsuper.app/countries/'

#---DATABASE_CONNECTION---
try:
    conn = pymysql.connect(
        host='localhost',
        user='root',
        password='password',
        database='vpn_api',
        cursorclass=pymysql.cursors.DictCursor
    )
    print("Connected to MySQL database")
except Exception as e:
    print(e)

# Define bypass list
bypass_list = [
    "localhost",
    "127.0.0.1",
    "172.16.*.*",
    "192.168.*.*",
    "twitter.com",
    "auth.grammarly.com",
    "www.netflix.com",
    "analytics.twitter.com",
    "login.microsoftonline.com",
    "api.twitter.com",
    "outlook.live.com",
    "pay.google.com",
    "dpf.authorize.net",
    "sg.p2pengine.net",
    "thepiratebay.org",
    "1337x.to",
    "limetorrents.info",
    "hackforums.net",
    "Black Hat blackhatworld.com",
    "Exploit exploit-db.com",
    "thehiddenwiki.org",
    "dirnxxdraygbifgc.onion",
    "deepdot35wvmeyd5.onion",
    "putlocker.is",
    "123movies.to",
    "fmovies.to",
    "scrapy.org",
    "octoparse.com",
    "Import.import.io",
    "bet365.com",
    "pokerstars.com",
    "draftkings.com",
    "pornhub.com",
    "xvideos.com",
    "redtube.com",
    "sendinblue.com",
    "mailgun.com",
    "sendgrid.com",
    "minergate.com",
    "nicehash.com",
    "Genesis genesis-mining.com"
]


def encrypt(text, project_code):

    cursor = conn.cursor()
    cursor.execute("SELECT * FROM project_keys WHERE project_code = %s", (project_code,))
    data = cursor.fetchone()

    key = data['key']
    start_index = int(data['start'])
    password = key[start_index:start_index+32]

    # Derive a key from the password using PBKDF2
    salt = b'salt_'
    derived_key = PBKDF2(password, salt, dkLen=32)
    cipher = AES.new(derived_key, AES.MODE_CBC)

    padded_data = pad(json.dumps(text).encode(), AES.block_size)
    encrypted_data = cipher.encrypt(padded_data)

    # Concatenate IV and encrypted data
    iv_and_data = cipher.iv + encrypted_data

    return base64.b64encode(iv_and_data).decode()


@app.route("/decrypt", methods=["POST"])
def decrypt_this():
    # Assuming connection and rncryptor are already defined
    encrypted_dataa = request.form['key']
    # cursor = connection.cursor()
    # cursor.execute("SELECT * FROM project_keys WHERE project_code = %s", (project_code,))
    # data = cursor.fetchone()

    # key = data['key']
    # start_index = int(data['start'])
    # password = key[start_index:start_index+32]
    
    password = "noGlXqC0j0O8H0iWrfa1ScYDININYDPQ"

    # Derive a key from the password using PBKDF2
    salt = b'salt_'
    derived_key = PBKDF2(password, salt, dkLen=32)

    # Decode base64 and separate IV and encrypted data
    encrypted_data = base64.b64decode(encrypted_dataa)
    iv = encrypted_data[:16]
    encrypted_data = encrypted_data[16:]

    # Create AES cipher in CBC mode with the derived key and IV
    cipher = AES.new(derived_key, AES.MODE_CBC, iv)

    # Decrypt the data and remove padding
    decrypted_data = unpad(cipher.decrypt(encrypted_data), AES.block_size)

    # Return the decrypted JSON data
    data = json.loads(decrypted_data.decode())
    return Response(data, content_type='application/json'), 200


def get_data(rows):
    ips = []
    for row in rows:
        countries = conn.cursor()
        countries.execute("""SELECT * FROM countries WHERE id = {};""".format(row['country_id']))
        countries = countries.fetchone()
        countryFlag = c_flag + countries['country_flag']
        ips.append({
            "proxy": row['ip_address'],
            "username": row['username'],
            "password": row['password'],
            "country": countries['country_code'],
            "countryName": countries['country_name'],
            "countryFlag": countryFlag,
            "scheme": row['protocol']
        })
    return ips


#---GETTING_IP_FROM_DATABASE---
@app.route("/get_IP", methods=["GET"])
def fetch_data_from_table():
    try:
        with conn.cursor() as cursor:
            cursor.execute("SELECT * FROM proxy_ips WHERE status='Active';")
            rows = cursor.fetchall()
            data = get_data(rows)
            data_dict = {
                "status": True,
                "message": "Server list fetched successfully",
                "data": {
                    "proxies": data
                },
                "bypass": bypass_list
            }
            json_response = json.dumps(data_dict, sort_keys=False)

            project_code = request.headers.get('X-Code')
            encrypted_text = encrypt(json_response, project_code)
            # print("IV:", iv)
            # print("Encrypted text:", encrypted_text)

            return Response(encrypted_text, content_type='application/json'), 200
    except pymysql.MySQLError as e:
        print(f"Error accessing MySQL database: {e}")

if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=8000)
