import os
import argparse
import json
import urllib3
import requests
from requests_ntlm import HttpNtlmAuth
# Use pip install requests_ntlm to install the necessary modules

class API(object):
    def __init__(self):
        if not ((os.environ.get('ITD_SHAREPOINT_PASS')) and (os.environ.get('ITD_SHAREPOINT_USER'))):
            print("\n*** ERROR: Environment Variables are not set for SharePoint ***")
            print("Set OS environment variables ITD_SHAREPOINT_PASS and ITD_SHAREPOINT_USER")
            exit(1)
        else:
            # Username is in the format of 'NDGOV\\<userName>'
            sp_user = os.environ['ITD_SHAREPOINT_USER']
            sp_pass = os.environ['ITD_SHAREPOINT_PASS']
    
            self.server_url = "https://share.nd.gov/"
            self.site_url = self.server_url + "itd/Computer-Systems/Distributed-Systems/VMWare/_api/web/"
            self.context_url = self.server_url + "itd/Computer-Systems/Distributed-Systems/VMWare/_api/contextinfo/"
            self.env = "All"
    
            self.headers = {
                "Accept":"application/json; odata=verbose",
                "Content-Type":"application/json; odata=verbose",
                "odata":"verbose",
                "X-RequestForceAuthentication":"true"
            }
    
            self.auth = HttpNtlmAuth(sp_user, sp_pass)
    
    def get_AllNodes(self):

        list_name = 'VM Guests'

        # Get list information
        requests.packages.urllib3.disable_warnings()
        r = requests.get(self.site_url + "lists/GetByTitle('%s')" % list_name, auth=self.auth, headers=self.headers, verify=False)
        list_guid = r.json()['d']['Id']
        list_itemcount = r.json()['d']['ItemCount']

        # Query list items
        api_items_url = self.site_url + "Lists(guid'%s')/Items" % list_guid
        concat_items = [] 
        # Parse the list
        requests.packages.urllib3.disable_warnings()
        cur_page = requests.get(api_items_url, auth=self.auth, headers=self.headers, verify=False)
        concat_items += cur_page.json()['d']['results']
        
        # Sharepoint uses pagination with '__next' in the JSON results to indicate additional pages of information
        # are present. Loop through the pages and concatenate the information into one dataset
        while '__next' in cur_page.json()['d']:
            requests.packages.urllib3.disable_warnings()
            cur_page = requests.get(cur_page.json()['d']['__next'], auth=self.auth, headers=self.headers, verify=False)
            concat_items += cur_page.json()['d']['results']

        return concat_items

    def get_ActiveNodes(self, e):

        self.env = e	
        list_name = 'VM Guests'

        # Get list information
        requests.packages.urllib3.disable_warnings()
        r = requests.get(self.site_url + "lists/GetByTitle('%s')" % list_name, auth=self.auth, headers=self.headers, verify=False)
        list_guid = r.json()['d']['Id']
        list_itemcount = r.json()['d']['ItemCount']

        # Query list items
        api_items_url = self.site_url + "Lists(guid'%s')/Items" % list_guid
        if self.env == 'All':
       	    active_items_url = api_items_url + "?$filter=(Status eq 'Current') or (Status eq 'Change')"
        else:
            active_items_url = api_items_url + "?$filter=(Environment eq '%s') and ((Status eq 'Current') or (Status eq 'Change'))" % self.env
        concat_items = []

        # Parse the list
        requests.packages.urllib3.disable_warnings()
        cur_page = requests.get(active_items_url, auth=self.auth, headers=self.headers, verify=False)
        concat_items += cur_page.json()['d']['results']

        # Sharepoint uses pagination with '__next' in the JSON results to indicate additional pages of information
        # are present. Loop through the pages and concatenate the information into one dataset
        while '__next' in cur_page.json()['d']:
            requests.packages.urllib3.disable_warnings()
            cur_page = requests.get(cur_page.json()['d']['__next'], auth=self.auth, headers=self.headers, verify=False)
            concat_items += cur_page.json()['d']['results']

        return concat_items

    def find_VM(self, hostname):

        domains = [".nd.gov", ".ndtestdev.nd.dev", ".ndcloud.gov", ".testnd.gov", ".itd.nd.gov", ".ns.nd.gov", ".cloudapp.azure.com", ".uat.mmis.nd.gov", ".test.ndcloud.gov", ".k12tst.nd.us", ".legend.nd.gov", ".tst.mmis.dev", ".trn.mmis.nd.gov", ".sit.mmis.nd.gov", ".nd.gov-mag", ".uat.mmis.dev", ".mo.legend.nd.gov", ".video.nd.gov", ".mmis.nd.gov", ".sit.legend.nd.gov", ".trn.mmis.dev", ".prm.mmis.nd.gov", ".state.nd.us", ".k12.nd.us", ".stg.k12.nd.us", ".sit.mmis.dev", "ndnic.com"]

        for domain in domains:
            try:
                data = self.get_Node(hostname + domain)
                if 'Title' in data[0]:
                    hostname = data[0]['Title']
                    break
            except:
                continue

        return(hostname)

    def get_Node(self, server):

        myNode = server
        list_name = 'VM Guests'

        # Get list information
        requests.packages.urllib3.disable_warnings()
        r = requests.get(self.site_url + "lists/GetByTitle('%s')" % list_name, auth=self.auth, headers=self.headers, verify=False)
        list_guid = r.json()['d']['Id']

        # Query list items
        api_items_url = self.site_url + "Lists(guid'%s')/Items" % list_guid
        singleServer_url = api_items_url + "?$filter=Title eq '%s'" % myNode
        cur_page = requests.get(singleServer_url, auth=self.auth, headers=self.headers, verify=False)

        return cur_page.json()['d']['results']

    def get_Agency(self, aID):

        agencyID = aID
        list_name = 'Agency'

        # Get list information
        requests.packages.urllib3.disable_warnings()
        r = requests.get(self.site_url + "lists/GetByTitle('%s')" % list_name, auth=self.auth, headers=self.headers, verify=False)
        list_guid = r.json()['d']['Id']

        # Query list items
        api_items_url = self.site_url + "Lists(guid'%s')/Items" % list_guid
        singleServer_url = api_items_url + "?$filter=ID eq '%s'" % agencyID
        cur_page = requests.get(singleServer_url, auth=self.auth, headers=self.headers, verify=False)

        return cur_page.json()['d']['results'][0]['Title']

    def get_AppName(self, appID):

        applicationID = appID
        list_name = 'VM App Name'

        # Get list information
        requests.packages.urllib3.disable_warnings()
        r = requests.get(self.site_url + "lists/GetByTitle('%s')" % list_name, auth=self.auth, headers=self.headers, verify=False)
        list_guid = r.json()['d']['Id']

        # Query list items
        api_items_url = self.site_url + "Lists(guid'%s')/Items" % list_guid
        singleServer_url = api_items_url + "?$filter=ID eq '%s'" % applicationID
        cur_page = requests.get(singleServer_url, auth=self.auth, headers=self.headers, verify=False)

        return cur_page.json()['d']['results'][0]['Title']

    def get_AppNodes(self, appID):

        applicationID = appID
        list_name = 'VM Guests'

        # Get list information
        requests.packages.urllib3.disable_warnings()
        r = requests.get(self.site_url + "lists/GetByTitle('%s')" % list_name, auth=self.auth, headers=self.headers, verify=False)
        list_guid = r.json()['d']['Id']

        # Query list items
        api_items_url = self.site_url + "Lists(guid'%s')/Items" % list_guid
        singleServer_url = api_items_url + "?$filter=AppName eq '%s'" % appID
        cur_page = requests.get(singleServer_url, auth=self.auth, headers=self.headers, verify=False)

        return cur_page.json()['d']['results']
