#!/bin/python3
import requests
import json
import sys, getopt
# from discord_webhook import DiscordWebhook

apiToken = "03f6f41f-2645-4d8d-a228-6fe7503ecb27"
discordHookUrl = 'https://discord.com/api/webhooks/969651301166231572/9z2aJcFtSEaFH6ObBEFzINtjacsN6TAAZiPRkzp5k5uJp1pNQFl6rhqi9nO9VmVMZG1T'
CurseFilesUrl = 'https://www.curseforge.com/minecraft/modpacks/pitek-3-0/files/'
BotUserName = 'PiTek-Updates'


headers = {
  'Accept': 'application/json',
  'X-Api-Token': f'{apiToken}'
}

def upload_Pack(file, displayName, ChangeLog):
#   changes = {'file': open(f'{ChangeLog}','r')}
  with open(f'{ChangeLog}.html','r') as clog:
    changes = str(clog.read())
  body = {
        "metadata": [
          {
              "changelog": f"{changes}",
              "changelogType": "html",
              "displayName": f"{displayName}",
              "releaseType": "alpha",
              "gameVersions": [9008]
          }
      ]
  }
  print(f"{changes}")
  files = {'file': open(f'{file}','rb')}
  try:
    req = requests.post('https://minecraft.curseforge.com/api/projects/255109/upload-file', files=files, headers = headers, data = body)
    # print(req)
    print("Full request")
    print(req.json())
    print("[0] request")
    print(req.json()[0])
    print("[1] request")
    print(req.json()[1])
    print("id request")
    print(req.json(id))
    print("[id] request")
    print(req.json([id]))
    sendWebhook("4325576", displayName, ChangeLog)
  except:
    sys.exit(1)
  #req = requests.post('https://minecraft.curseforge.com/api/projects/255109/upload-file', files=files, headers = headers, data = body)
  #print(req.json())
  #print("Working")




def sendWebhook(id, displayName, ChangeLog):
  # webhook = DiscordWebhook(url='', content='Test Webhook')
  # response = webhook.execute()
  with open(f'{ChangeLog}.md','r') as clog:
    changesMD = str(clog.read())
  print("Changelog Printed Below")
  print(changesMD)

  url = discordHookUrl

  #for all params, see https://discordapp.com/developers/docs/resources/webhook#execute-webhook
  data = {
      # "content" : "",
      "username" : f"{BotUserName}"
  }

  #for all params, see https://discordapp.com/developers/docs/resources/channel#embed-object
  data["embeds"] = [
      {
          "description" : f"{changesMD}",
          "title" : f"{displayName}",
          "url" : f"{CurseFilesUrl}{id}"
      }
  ]

  result = requests.post(url, json = data)

  try:
      result.raise_for_status()
  except requests.exceptions.HTTPError as err:
      print(err)
  else:
      print("Payload delivered successfully, code {}.".format(result.status_code))




def setArgs(argv):
    arg_file = ""
    arg_displayname = ""
    arg_changelog = ""
    arg_help = "{0} -f '<file>' -d '<displayname>' -c '<changelog_file.txt>'".format(argv[0])
    
    try:
        opts, args = getopt.getopt(argv[1:], "h:f:d:c:", ["help", "file=", 
        "displayname=", "changelog="])
    except:
        print(arg_help)
        sys.exit(2)
    
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            print(arg_help)  # print the help message
            sys.exit(2)
        elif opt in ("-f", "--file"):
            arg_file = arg
        elif opt in ("-d", "--displayname"):
            arg_displayname = arg
        elif opt in ("-c", "--changelog"):
            arg_changelog = arg
    print('file:', arg_file)
    print('displayname:', arg_displayname)
    print('changelog:', arg_changelog)
    upload_Pack(arg_file, arg_displayname, arg_changelog)

if __name__ == "__main__":
    setArgs(sys.argv)