import json
import os
import pickle as pkl
import shutil

import numpy as np
import requests

from .config import DATA_FILES_PATH, RAVENVERSE_URL, TEMP_FILES_PATH
from .globals import globals as g

import urllib.request
from pip._internal.operations.freeze import freeze

def isLatestVersion(pkgName):
    # Get the currently installed version
    current_version = ''
    for requirement in freeze(local_only=False):
        pkg = requirement.split('==')
        if pkg[0] == pkgName:
            current_version = pkg[1]

    # Check pypi for the latest version number
    contents = urllib.request.urlopen('https://pypi.org/pypi/'+pkgName+'/json').read()
    data = json.loads(contents)
    latest_version = data['info']['version']

    # print('Current version of '+pkgName+' is '+current_version)
    # print('Latest version of '+pkgName+' is '+latest_version)

    return latest_version <= current_version

def save_data_to_file(data_id, data):
    """
    Method to save data in a pickle file
    """
    file_path = os.path.join(DATA_FILES_PATH, "data_{}.json".format(data_id))

    if os.path.exists(file_path):
        os.remove(file_path)

    os.makedirs(os.path.dirname(file_path), exist_ok=True)
    with open(file_path, "w") as f:
        if isinstance(data, np.ndarray):
            data = data.tolist()
        json.dump(data, f)

    return file_path


def load_data_from_file():
    pass


def delete_data_file(data_id):
    file_path = os.path.join(DATA_FILES_PATH, "data_{}.json".format(data_id))
    if os.path.exists(file_path):
        os.remove(file_path)


def copy_data(source, destination):
    try:
        shutil.copy(source, destination)
        print("File copied successfully.")
    # If source and destination are same
    except shutil.SameFileError:
        print("Source and destination represents the same file.")
    # If there is any permission issue
    except PermissionError:
        print("Permission denied.")
    # For other errors
    except:
        print("Error occurred while copying file.")


def make_request(endpoint, method, payload={}, headers=None):
    headers = {"token": g.ravenverse_token}
    if method == "post":
        return requests.post(
            "{}/{}".format(RAVENVERSE_URL, endpoint), json=payload, headers=headers
        )
    elif method == "get":
        return requests.get(
            "{}/{}".format(RAVENVERSE_URL, endpoint), headers=headers
        )


def convert_to_ndarray(x):
    if isinstance(x, str):
        x = np.array(json.loads(x))
    elif isinstance(x, list) or isinstance(x, tuple) or isinstance(x, int) or isinstance(x, float):
        x = np.array(x)

    return x


def convert_ndarray_to_str(x):
    return str(x.tolist())


def dump_data(data_id, graph_id, value):
    """
    Dump ndarray to file
    """
    file_path = os.path.join(TEMP_FILES_PATH, "data_{}_{}.pkl".format(data_id, graph_id))
    if os.path.exists(file_path):
        os.remove(file_path)
    os.makedirs(os.path.dirname(file_path), exist_ok=True)
    with open(file_path, "wb") as f:
        pkl.dump(value, f)
    return file_path
