import gzip
import collections
from flask import make_response, json, current_app
import numpy as np
import pandas as pd
import khayyam as kym
from app.errors import *
import gc
import requests


def response_message(data=None, status=200):
    if status != 200:
        try:
            error = {'fa': data.message_fa, 'en': data.message_en}
        except AttributeError:
            print(data)
            error = MethodError()
            error = {'message_fa': error.message_fa, 'message_en': error.message_en}
        resp_dict = {'message': error}
    else:
        resp_dict = data
    resp_dict = json.loads(json.dumps(resp_dict, default=convert, sort_keys=False).replace('"None"', 'null')
                           .replace('NaN', 'null'), strict=False)
    content = gzip.compress(json.dumps(resp_dict, ensure_ascii=False, indent=3, default=convert,
                                       sort_keys=False).encode('utf8'), 5)
    response = make_response(content, status)
    response.headers['Content-length'] = len(content)
    response.headers['Content-Encoding'] = 'gzip'
    response.headers['Content-Type'] = 'application/json; charset=utf-8'
    response.headers.add('Access-Control-Allow-Origin', '*')
    gc.collect()
    return response


def deep_dict_update(d, u):
    for k, v in u.items():
        if isinstance(v, collections.abc.Mapping):
            d[k] = deep_dict_update(d.get(k, {}), v)
        else:
            d[k] = v
    return d


def convert(o):
    if isinstance(o, np.int64):
        return int(o)
    if isinstance(o, np.bool_):
        if o:
            return True
        else:
            return False
    if pd.isna(o):
        return None
    if o is np.ma.masked:
        return None
    json.dumps(o)
