import sys
import os
import json
import argparse # use argparse to parse the arguments
from subprocess import call
from time import strftime
from site24x7_plugin_helper.connector.database_client import DatabaseClient as Client

PASS_DATABASE_CONNECTION = True
class DatabaseClient(Client):
    def database_type(self):
        return "MSSQL"

def special_strftime():
    ''' expected output: Aug 22nd, 2022 '''
    dic = {
        '01':'st,','21':'st,','31':'st,',
        '02':'nd,','22':'nd,',
        '03':'rd,','23':'rd,'
    }
    x = strftime('%b %d')
    year = strftime(' %Y')
    return x + dic.get(x[-2:], 'th,') + year

if __name__ == "__main__":
    # server informations are given as arguments
    server = sys.argv[1]
    database = sys.argv[2]
    username = sys.argv[3]
    password = sys.argv[4]
    driver_location = sys.argv[5] # /opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.5.so.1.1
    query = sys.argv[6]
    this_plugin_name = sys.argv[7]
    cache = {
        #"server":server,
        "database":database,
        #"username":username,
        #"password":password,
        #"driver_location":driver_location,
        "query":query,
        "this_plugin_name":this_plugin_name,
    }
    if not PASS_DATABASE_CONNECTION:
        DatabaseClient = DatabaseClient(server, database, username, password, driver_location)
        cursor = DatabaseClient.cursor
        print("connnected")
        # existing query that returns all rows from the table for caching
        # 'EXEC [Ultramerchant].dbo.pr_membership_credit_billing_stats_24x7_monitor_sel'
        rows = DatabaseClient.fetchall(query)
        for i in enumerate(rows):
            key = rows[i][1]
            value = rows[i][2]
            cache[key] = value
    # # validate data before saving to cache
    # ww = connector.validatePluginData(cache)
    # breakpoint() 
    # save cache to file as this_plugin_name 
    cache_file_name = "/tmp/" + this_plugin_name + ".cache"
    open(cache_file_name, 'w', encoding='utf8').write(
        json.dumps(cache, indent=4)
    )
    print(json.dumps(cache, indent=4, sort_keys=True))

    SITE24x7_LOCATION = "/opt/site24x7/monagent/plugins"
    folder_destination = os.path.join(SITE24x7_LOCATION, this_plugin_name)
    file_destination = os.path.join(folder_destination, this_plugin_name + ".py")
    print("folder_destination: " + folder_destination)
    print("file_destination: " + file_destination)
    # BELOW PROCESS WILL BE DONE BY JENKINS
    # BECAUSE IT IS BREAKING PATH LOCATION WITH //
    # /opt/site24x7/monagent/plugins
    # create a folder if not exists
    if not os.path.exists(folder_destination):
        call(f"mkdir {folder_destination}", shell=True)
        #os.mkdir(folder_destination)

    # create a python file if not exists
    if not os.path.isfile(file_destination):
        call(f"touch {file_destination}", shell=True)
        open(file_destination, 'w', encoding="utf8").write(f"""#!/usr/bin/env python3
'''
   this file is generated by Jenkins on {special_strftime()}
'''
from site24x7_plugin_helper.connector.cache_client import CacheClient

CacheClient = CacheClient(
    "{cache_file_name}",
    author="Renas Mirkan Kilic",
    plugin_version="1",
    date_created="{special_strftime()}"
)

def metric_collector():
    data = {{}}
    try:
        CacheClient.set_metric_types()
        data.update(CacheClient.dict)
    except Exception as err:
        data["error"] = str(err)
    CacheClient.__setitem__("thisPluginName", "{this_plugin_name}")
    return data

if __name__ == "__main__":
    result = metric_collector()
    print(CacheClient.dumps(result))
""" )
