from discord.ext import commands
import discord
import pymysql
import os
from mcrcon import MCRcon

password = open("../sqlPass.txt", 'r').read()

con = pymysql.connect(host='localhost',
                      user='Bot',
                      password=f'{password}',
                      db='serverIDs',
                      charset='utf8mb4',
                      port=5618,
                      cursorclass=pymysql.cursors.DictCursor)


def change(ip1, ip2):
    print(ip1+' '+ip2)

    os.system("systemctl disable mc mcL mcP mcEvent1 mcEvent2")

    with con:
        cur = con.cursor()
        cur.execute(f"SELECT * FROM Bot.McServer where serverIP = {ip1}")
        server1 = cur.fetchall()

        cur.execute(f"SELECT * FROM Bot.McServer where serverIP = {ip2}")
        server2 = cur.fetchall()

        cur.execute("SELECT serverRCON FROM Bot.McServer ORDER BY serverRCON DESC")
        allServerRcon = cur.fetchall()

    os.system("systemctl stop mc mcL mcP mcEvent1 mcEvent2")

    for i in range(len(allServerRcon)):
        print("192.168.1.52 " + f"{password} " + allServerRcon[i]['serverRCON'] + "________________________________________________________________________________________________")

    for i in range(len(allServerRcon)):
        with MCRcon("192.168.1.52", f"{password}", allServerRcon[i]['serverRCON']) as mcr:
            mcr.command("stop")

    f = open("/etc/systemd/system/mcEvent1.service", "w")

    # f = open("text.txt", 'w')
    f.write(
        f"""\
[Unit]
Description=Minecraft Server
After=network.target
StartLimitIntervalSec=0

[Service]
Type=simple
Restart=always
RestartSec=1
User=officereso
group=minecraft
ExecStart=/usr/bin/java  -jar -Xmx4000m -Xms4000m {server1[0]['serverJarPath']}
WorkingDirectory={server1[0]['workingDirectory']}

[install]
WantedBy=multi-user.target\
"""
    )
    f.close()

    f = open("/etc/syst1md/system/mcEvent2.service", "w")

    # f = open("text2.txt", 'w')
    f.write(
        f"""\
[Unit]
Description=Minecraft Server
After=network.target
StartLimitIntervalSec=0

[Service]
Type=simple
Restart=always
RestartSec=1
User=officereso
group=minecraft
ExecStart=/usr/bin/java  -jar -Xmx4000m -Xms4000m {server2[0]['serverJarPath']}
WorkingDirectory={server2[0]['workingDirectory']}

[install]
WantedBy=multi-user.target\
"""
    )
    f.close()

    f = open("/home/officereso/mcserver/lobby/plugins/ServerSelectorX/menu/default.yml")

    f.write(f"""\
# Number of rows of slots of your server selector menu. For example '2' will mean 2*9 = 18 slots. Max value is 6.
rows: 2

# This will be displayed as the title of the menu.
title: 'Server Selector'

# This will be the name of the server selector item
item-name: 'Server Selector'

item-lore:
- 'Line 1'
- 'Line 2'

# The name of the server selector item.
item: COMPASS

# Give the item when a player joins?
on-join: true

# What slot should the item be in? Specify -1 to automatically put it in the first available slot.
inv-slot: 0

# URL clickable message
url-message: '&3&lClick here'

# Command to open the menu. Specify "none" for no command. (without /)
command: "menu"

# https://github.com/ServerSelectorX/ServerSelectorX/wiki/Free-%7C-Items-in-the-server-selector
menu:

  # Server item
  3:
  
    # Server pinging help: https://github.com/ServerSelectorX/ServerSelectorX/wiki/Free-%7C-Server-Pinging
    # With server pinging disabled, the placeholders don't work and the plugin will always use the offline section.
    ping-server: false
    ip: 66.69.103.65
    port: 25569
    
    # Action to run when the item is clicked
    action: 'srv:plots'

    online:
      item: COMMAND_BLOCK
      name: '&aPlots Server'


    offline:
      item: COMMAND_BLOCK
      name: '&aPlots Server'


  # Message item
  5:
  
    # Server pinging help: https://github.com/ServerSelectorX/ServerSelectorX/wiki/Free-%7C-Server-Pinging
    # With server pinging disabled, the placeholders don't work and the plugin will always use the offline section.
    ping-server: {"false" if server1[0]['selectorPing'] == 0 else "true"}
    ip: 192.168.1.52
    port: {server1[0]['serverIP']}
    
    # Action to run when the item is clicked
    action: 'srv:{server1[0]['action']}'

    online:
      item: {server1[0]['selectorItem']}
      name: '{server1[0]['selectorTextColor']}{server1[0]['serverName']}'
      lore:
        - {server1[0]['selectorLore']}


    offline:
      item: {server1[0]['selectorItem']}
      name: '{server1[0]['selectorTextColor']}{server1[0]['serverName']}'
      lore:
        - {server1[0]['selectorLore']}
      
      
  13:
  
    # Server pinging help: https://github.com/ServerSelectorX/ServerSelectorX/wiki/Free-%7C-Server-Pinging
    # With server pinging disabled, the placeholders don't work and the plugin will always use the offline section.
    ping-server: false
    ip: 66.69.103.65
    port: 25567
    
    # Action to run when the item is clicked
    action: 'srv:{server2[0]['action']}'

    online:
      item: {server2[0]['selectorItem']}
      name: '{server2[0]['selectorTextColor']}{server2[0]['serverName']}'
      lore:
        - {server2[0]['selectorLore']}


    offline:
      item: {server2[0]['selectorItem']}
      name: '{server2[0]['selectorTextColor']}{server2[0]['serverName']}'
      lore:
        - {server2 [0]['selectorLore']}

  # No action item
  -1: # -1 means everything else
    action: 'none'
    offline:
      item: LIGHT_GRAY_STAINED_GLASS_PANE\
""")
    f.close()

    os.system("systemctl daemon-reload")
    os.system("systemctl enable mc mcL mcP mcEvent1 mcEvent2")
    os.system("systemctl start mc mcL mcP mcEvent1 mcEvent2")


class Change(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command(pass_context=True, name="change")
    async def change_server(self, ctx, ip1: int, ip2: int):
        print(ctx.author.id)
        if ctx.author.id != 305589587215122432:
            return
        change(ip1, ip2)


def setup(client):
    client.add_cog(Change(client))
