import time
from datetime import datetime
import os
import json
import sys
import os.path
import requests
import urllib3
import socket
from app.libraries.database import Database
from app.libraries.setup import Setup

def is_json(myjson):

    try:
        json_object = json.loads(myjson)
    except ValueError as e:
        return False
    return True

class Nodeinfo():

    name = "Query server nodeinfo data"

    def __init__(self, server=None, db=None, setup=None, soft=None, soft_version=None, version=None, users=None, mau=None, alive=False):

        self.server = server
        self.db = Database()
        self.setup = Setup()
        self.soft = ''
        self.soft_version = ''
        self.users = 0
        self.mau = 0
        self.alive = alive

    def getdata(self, server, api):

        if server.find(".") == -1:
            return
        if server.find("@") != -1:
            return
        if server.find("/") != -1:
            return
        if server.find(":") != -1:
            return

        url = 'https://' + server

        self.soft = ''
        self.soft_version = ''
        self.users = 0
        self.mau = 0
        self.alive = False

        try:

            response = requests.get(url + api, headers = self.setup.user_agent, timeout=3)

            if response.status_code == 200:

                try:

                    self.soft = response.json()['software']['name']
                    self.soft = self.soft.lower()
                    self.soft_version = response.json()['software']['version']
                    self.users = response.json().get('usage').get('users').get('total') or '0'
                    if int(self.users) > 1500000:
                        return
                    self.mau = response.json().get('usage').get('users').get('activeMonth') or 0

                    self.alive = True

                    print(f"Server {server} ({self.soft} {self.soft_version}) is alive!")
                    print('*********************************************************************')

                except:

                    Nodeinfo.pending_servers = Nodeinfo.pending_servers - 1
                    pass

        except:

            pass

        return (server, self.soft, self.soft_version, self.users, self.mau, self.alive)
