import requests
import json
import gzip
from main import df
import pandas as pd

kairosdb_server = "http://192.168.0.220:8080"
kairos_url = "http://192.168.0.220:8080/api/v1/datapoints/query"

# Simple test [without compression]
# pushdata_kdb():
data = [
    {
        "name": "sneha",
        "datapoints": df[['Datetime', 'RH']].values.tolist(),
        "tags": {"project": "kairos"}
    }
]

response = requests.post(kairosdb_server + "/api/v1/datapoints", json.dumps(data))
print("Simple test [without compression]: \t%d (status code)" % response.status_code)


# query my data of max temperature for yearly monthly and weekly
def maxtemp(query):
    if query == "months":
        payload = json.dumps({

                "metrics": [
                    {
                        "tags": {
                            "project": [
                                "kairos"
                            ]
                        },
                        "name": "sneha",
                        "aggregators": [
                            {
                                "name": "max",
                                "sampling": {
                                    "value": "1",
                                    "unit": "months"
                                }
                            }
                        ]
                    }
                ],
                "plugins": [],
                "cache_time": 0,
                "start_absolute": 1094668200000,
                "end_absolute": 1112553000000
            })
        headers = {
            'Content-Type': 'application/json'
        }

        response = requests.request("POST", kairos_url, headers=headers, data=payload)

        return response.json()

    elif query == "weeks":
        payload = json.dumps({

                "metrics": [
                    {
                        "tags": {
                            "project": [
                                "kairos"
                            ]
                        },
                        "name": "sneha",
                        "aggregators": [
                            {
                                "name": "max",
                                "sampling": {
                                    "value": "1",
                                    "unit": "weeks"
                                }
                            }
                        ]
                    }
                ],
                "plugins": [],
                "cache_time": 0,
                "start_absolute": 1094668200000,
                "end_absolute": 1112553000000
            })
        headers = {
            'Content-Type': 'application/json'
        }
        response = requests.request("POST", kairos_url, headers=headers, data=payload)

        return response.json()

    elif query == "days":
        payload = json.dumps({

                "metrics": [
                    {
                        "tags": {
                            "project": [
                                "kairos"
                            ]
                        },
                        "name": "sneha",
                        "aggregators": [
                            {
                                "name": "max",
                                "sampling": {
                                    "value": "1",
                                    "unit": "days"
                                }
                            }
                        ]
                    }
                ],
                "plugins": [],
                "cache_time": 0,
                "start_absolute": 1094668200000,
                "end_absolute": 1112553000000
            })
        headers = {
            'Content-Type': 'application/json'
        }

        response = requests.request("POST", kairos_url, headers=headers, data=payload)

        return response.json()

    else:
        return {"failed": "data out of format"}


# query my data of min temperature for yearly monthly and weekly
def mintemp(query):
    if query == "months":
        payload = json.dumps({

                "metrics": [
                    {
                        "tags": {
                            "project": [
                                "kairos"
                            ]
                        },
                        "name": "sneha",
                        "aggregators": [
                            {
                                "name": "min",
                                "sampling": {
                                    "value": "1",
                                    "unit": "months"
                                }
                            }
                        ]
                    }
                ],
                "plugins": [],
                "cache_time": 0,
                "start_absolute": 1094668200000,
                "end_absolute": 1112553000000
            })
        headers = {
            'Content-Type': 'application/json'
        }

        response = requests.request("POST", kairos_url, headers=headers, data=payload)

        return response.json()


    elif query == "weeks":
        payload = json.dumps({

                "metrics": [
                    {
                        "tags": {
                            "project": [
                                "kairos"
                            ]
                        },
                        "name": "sneha",
                        "aggregators": [
                            {
                                "name": "min",
                                "sampling": {
                                    "value": "1",
                                    "unit": "weeks"
                                }
                            }
                        ]
                    }
                ],
                "plugins": [],
                "cache_time": 0,
                "start_absolute": 1094668200000,
                "end_absolute": 1112553000000
            })
        headers = {
            'Content-Type': 'application/json'
        }

        response = requests.request("POST", kairos_url, headers=headers, data=payload)

        return response.json()

    elif query == "days":
        payload = json.dumps({

                "metrics": [
                    {
                        "tags": {
                            "project": [
                                "kairos"
                            ]
                        },
                        "name": "sneha",
                        "aggregators": [
                            {
                                "name": "min",
                                "sampling": {
                                    "value": "1",
                                    "unit": "days"
                                }
                            }
                        ]
                    }
                ],
                "plugins": [],
                "cache_time": 0,
                "start_absolute": 1094668200000,
                "end_absolute": 1112553000000
            })
        headers = {
            'Content-Type': 'application/json'
        }

        response = requests.request("POST", kairos_url, headers=headers, data=payload)

        return response.json()

    else:
        return {"failed": "data out of format"}


# query my data of avg temperature for yearly monthly and weekly
def avgtemp(query):
    if query == "months":
        payload = json.dumps({

                "metrics": [
                    {
                        "tags": {
                            "project": [
                                "kairos"
                            ]
                        },
                        "name": "sneha",
                        "aggregators": [
                            {
                                "name": "avg",
                                "sampling": {
                                    "value": "1",
                                    "unit": "months"
                                }
                            }
                        ]
                    }
                ],
                "plugins": [],
                "cache_time": 0,
                "start_absolute": 1094668200000,
                "end_absolute": 1112553000000
            })
        headers = {
            'Content-Type': 'application/json'
        }

        response = requests.request("POST", kairos_url, headers=headers, data=payload)

        return response.json()

    elif query == "weeks":
        payload = json.dumps({

                "metrics": [
                    {
                        "tags": {
                            "project": [
                                "kairos"
                            ]
                        },
                        "name": "sneha",
                        "aggregators": [
                            {
                                "name": "avg",
                                "sampling": {
                                    "value": "1",
                                    "unit": "weeks"
                                }
                            }
                        ]
                    }
                ],
                "plugins": [],
                "cache_time": 0,
                "start_absolute": 1094668200000,
                "end_absolute": 1112553000000
            })
        headers = {
            'Content-Type': 'application/json'
        }

        response = requests.request("POST", kairos_url, headers=headers, data=payload)

        return response.json()

    elif query == "days":
        payload = json.dumps({

                "metrics": [
                    {
                        "tags": {
                            "project": [
                                "kairos"
                            ]
                        },
                        "name": "sneha",
                        "aggregators": [
                            {
                                "name": "avg",
                                "sampling": {
                                    "value": "1",
                                    "unit": "days"
                                }
                            }
                        ]
                    }
                ],
                "plugins": [],
                "cache_time": 0,
                "start_absolute": 1094668200000,
                "end_absolute": 1112553000000
            })
        headers = {
            'Content-Type': 'application/json'
        }

        response = requests.request("POST", kairos_url, headers=headers, data=payload)

        return response.json()
    else:
        return {"failed": "data out of format"}


# function to collect all the values convert into df and then to excel(list of list)
def dailytempdata():

    MAX_temp = maxtemp("days")['queries'][0]['results'][0]['values']
    MIN_temp = mintemp("days")['queries'][0]['results'][0]['values']
    AVG_temp = avgtemp("days")['queries'][0]['results'][0]['values']

    df1 = pd.DataFrame(MAX_temp, columns=["Updated_Date", "max"])
    df2 = pd.DataFrame(MIN_temp, columns=["Updated_Date", "min"])
    df3 = pd.DataFrame(AVG_temp, columns=["Updated_Date", "avg"])

    a = pd.merge(df1, df2, on="Updated_Date")
    b = pd.merge(a, df3, on="Updated_Date")
    b['Updated_Date'] = pd.to_datetime(a['Updated_Date'], unit='ms')
    b['Updated_Date'] = b['Updated_Date'].dt.strftime('%Y-%m-%d')
    b.to_excel("scripts/Data/dailyreport.xlsx")
    fpath = 'scripts/Data/'
    fname = 'dailyreport.xlsx'
    filepath = fpath + fname
    return filepath, fname


def monthlytempdata():
    MAX_temp = maxtemp("months")['queries'][0]['results'][0]['values']
    MIN_temp = mintemp("months")['queries'][0]['results'][0]['values']
    AVG_temp = avgtemp("months")['queries'][0]['results'][0]['values']
    df1 = pd.DataFrame(MAX_temp, columns=["Updated_Date", "max"])
    df2 = pd.DataFrame(MIN_temp, columns=["Updated_Date", "min"])
    df3 = pd.DataFrame(AVG_temp, columns=["Updated_Date", "avg"])

    a = pd.merge(df1, df2, on="Updated_Date")
    b = pd.merge(a, df3, on="Updated_Date")
    b['Updated_Date'] = pd.to_datetime(a['Updated_Date'], unit='ms')
    b['Updated_Date'] = b['Updated_Date'].dt.strftime('%Y-%m-%d')
    b.to_excel("scripts/Data/monthreport.xlsx", index=False)
    path = 'scripts/Data/'
    fname = 'monthreport.xlsx'
    filepath = path + fname
    return filepath, fname


def weeklytempdata():
    MAX_temp = maxtemp("weeks")['queries'][0]['results'][0]['values']
    MIN_temp = mintemp("weeks")['queries'][0]['results'][0]['values']
    AVG_temp = avgtemp("weeks")['queries'][0]['results'][0]['values']
    df1 = pd.DataFrame(MAX_temp, columns=["Updated_Date", "max"])
    df2 = pd.DataFrame(MIN_temp, columns=["Updated_Date", "min"])
    df3 = pd.DataFrame(AVG_temp, columns=["Updated_Date", "avg"])

    a = pd.merge(df1, df2, on="Updated_Date")
    b = pd.merge(a, df3, on="Updated_Date")
    b['Updated_Date'] = pd.to_datetime(a['Updated_Date'], unit='ms')
    b['Updated_Date'] = b['Updated_Date'].dt.strftime('%Y-%m-%d')
    b.to_excel("scripts/Data/weekreport.xlsx", index=False)
    path = 'scripts/Data/'
    fname = 'weekreport.xlsx'
    filepath = path + fname
    return filepath, fname


# def dailytempdata():
#     return None