#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
The MIT License (MIT)

Copyright (c) Andrew Brookes 2021
andybrookestar[small snail]gmail[period]com
aka captainsensible 
aka andybrookestar

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to 
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
 the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
 DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
   SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
See https://opensource.org/licenses/MIT for details
"""
import operator
from operator import itemgetter
import requests
import time
import os
import tkinter as tk
from tkinter import ttk
import re
import sys
from tkinter.messagebox import showinfo
from tkinter import font

user = os.getenv("SUDO_USER")
if user is None:
    print (" re-run this program using  'sudo'" )
    sys.exit()



Worldwide1="""#Server = http://mirror.rackspace.com/archlinux/$repo/os/$arch
#Server = https://mirror.rackspace.com/archlinux/$repo/os/$arch
"""

# next def is evoked by process button
def button_clicked():
    var.set('ok working on it ')
   # res = requests.get('https://archlinux.org/mirrorlist/all/')
    t=selected.get()
    print(t)



    #choice 1 populate mirrorlist none enabled    
    if t =="1":
        res = requests.get('https://archlinux.org/mirrorlist/all/')
        myvar= res.text
        file = open('/etc/pacman.d/mirrorlist' , 'w')
        file.write(myvar)
        file.close()
        var.set("done ")
    #choice 2 populate and enable all        
    elif t =='2':
         res = requests.get('https://archlinux.org/mirrorlist/all/') 
         myvar= res.text
         newvar = re.sub(r'[#](?!#)', " ", myvar)
         file = open('/etc/pacman.d/mirrorlist' , 'w')
         file.write(newvar)
         file.close()
         var.set("done ")   
    
    elif t=='3':
             
        d= countries.get()
        if d=="select nearest Country":
             var.set("please also choose a country from drop down")
        
        elif d=="Worldwide":
            t=countryMirrors(Worldwide1)
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        elif d=="Australia":
            t=countryMirrorsLive('AU')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        elif d=="Austria":
            t=countryMirrorsLive('AT')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        elif d=="Bangladesh":
            t=countryMirrorsLive('BD')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        elif d=="Belarus":
            t=countryMirrorsLive('BY')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        elif d=="Belgium":
            t=countryMirrorsLive('BE')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        
        elif d=="BosniaNHezegovia":
            t=countryMirrorsLive('BA')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        elif d=="Brazil":
            t=countryMirrorsLive('BR')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist")           
                    
        elif d=="Bulgaria":
            t=countryMirrorsLive('BG')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
                 
                    
        elif d=="Cambodia":
            t=countryMirrorsLive('KH')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
                  
                    
        elif d=="Canada":
            t=countryMirrorsLive('CA')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        elif d=="Chile":
            t=countryMirrorsLive('CL')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        elif d=="China":
            t=countryMirrorsLive('CN')
            if t =="done":
                       var.set("done written to /etc/pacman.d/mirrorlist") 
           
      
       
        elif d=="Colombia":
            t=countryMirrorsLive('CO')
            if t =="done":
                       var.set("done written to /etc/pacman.d/mirrorlist") 
       
        elif d=="Croatia":
            t=countryMirrorsLive('HR')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        elif d=="Czechia":
            t=countryMirrorsLive('CZ')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
         
        elif d=="Denmark":
            t=countryMirrorsLive('DK')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist")  
        
        elif d=="Ecuador":
            t=countryMirrorsLive('EC')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist")   
        elif d=="Estonia":
            t=countryMirrorsLive('EE')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist")   
        elif d=="Finland":
            t=countryMirrorsLive('FL')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist")   
         
        
        
        elif d=="France":
            t=countryMirrorsLive('FR')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist")   
         
        
        
        elif d=="Georgia":
            t=countryMirrorsLive('GE')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist")   
        
        
        elif d=="Germany":
            t=countryMirrorsLive('DE')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist")   
        
        
        elif d=="Greece":
            t=countryMirrorsLive('GR')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist")   
         
        elif d=="HongKong":
            t=countryMirrorsLive('HK')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist")   
          
        elif d=="Hungary":
            t=countryMirrorsLive('HU')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist")   
                    
        elif d=="Iceland":
            t=countryMirrorsLive('IS')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist")               
        
        
        
        elif d=="India":
            t=countryMirrorsLive('IN')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        
        elif d=="Indonesia":
            t=countryMirrorsLive('ID')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        
        
        elif d=="Iran":
            t=countryMirrorsLive('IR')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        elif d=="Ireland":
            t=countryMirrorsLive('IE')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
         
         
        elif d=="Israel":
            t=countryMirrorsLive('IL')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
         
         
        elif d=="Italy":
            t=countryMirrorsLive('IT')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
       
       
        elif d=="Japan":
            t=countryMirrorsLive('JP')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
       
        
        elif d=="Kazakhstan":
            t=countryMirrorsLive('KZ')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        
        elif d=="Kenya":
            t=countryMirrorsLive('KE')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        elif d=="Latvia":
            t=countryMirrorsLive('LV')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        
        elif d=="Lithuania":
            t=countryMirrorsLive('LT')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        
        
        elif d=="Luxembourg":
            t=countryMirrorsLive('LU')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        
        elif d=="Mexico":
            t=countryMirrorsLive('MX')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        
        elif d=="Moldova":
            t=countryMirrorsLive('MD')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        elif d=="Monaco":
            t=countryMirrorsLive('MC')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist")  
        
        
        
        elif d=="Netherlands":
            t=countryMirrorsLive('NL')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        
        elif d=="NewCaledonia":
            t=countryMirrorsLive('NC')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        
        
        elif d=="NewZealand":
            t=countryMirrors('NZ')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        elif d=="North Macedonia":
            t=countryMirrorsLive('MK')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        
        elif d=="Norway":
            t=countryMirrorsLive('NO')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        
        
        
        elif d=="Pakistan":
            t=countryMirrorsLive('PK')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        
        
        elif d=="Paraguay":
            t=countryMirrorsLive('PY')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
        
        elif d=="Poland":
            t=countryMirrorsLive('PL')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
       
        elif d=="Portugal":
            t=countryMirrorsLive('PT')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
       
        elif d=="Romania":
            t=countryMirrorsLive('RO')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
       
        elif d=="'Russia":
            t=countryMirrorsLive('RU')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
       
       
        elif d=="Reunion":
            t=countryMirrorsLive('RE')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
       
        elif d=="Serbia":
            t=countryMirrorsLive('RS')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
       
       
        elif d=="Singapore":
            t=countryMirrorsLive('SG')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
       
       
        elif d=="Slovakia":
            t=countryMirrorsLive('SK')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        elif d=="Slovenia":
            t=countryMirrorsLive('SI')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
         
       
        elif d=="South Africa":
            t=countryMirrorsLive('ZA')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        elif d=="South Korea":
            t=countryMirrorsLive('KR')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist")  
        elif d=="Spain":
            t=countryMirrorsLive('ES')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        elif d=="Sweden":
            t=countryMirrorsLive('SE')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
       
     
       
        elif d=="Switzerland":
            t=countryMirrorsLive('CH')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
       
       
       
       
        elif d=="Taiwan":
            t=countryMirrorsLive('TW')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
        
       
       
        elif d=="Thailand":
            t=countryMirrorsLive('TH')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
       
       
        elif d=="Turkey":
            t=countryMirrorsLive('TR')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
       
       
        elif d=="Ukraine":
            t=countryMirrorsLive('UA')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
       
       
        elif d=="United Kingdom":
            t=countryMirrorsLive('GB')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
       
       
        elif d=="USA":
            t=countryMirrorsLive('US')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
       
       
        elif d=="Vietnam":
            t=countryMirrorsLive('VN')
            if t =="done":
                    var.set("done written to /etc/pacman.d/mirrorlist") 
       
       
        else:
           
                 print ("i have no clue what you picked")
                 
    
               
            
               
           # here do all filtering of string get time elapsed and write to /etc/pacman.d/mirrors


def countryMirrorsLive(somevar):
	myVar=somevar
	myDic ={}
	res=requests.get('https://archlinux.org/mirrorlist/?country='+myVar)
	mirrorString =res.text
	lines= mirrorString.splitlines()
	for line in lines:
		
		 
		z= re.match(r'[#](?!#)',line)
		if z:
			print(line)
			t=re.sub(r'(#Server\s=)', "",line)  
			try:
				times=(requests.get(t,timeout=2).elapsed.total_seconds())
				myDic[t]=times 
			except:
				print ("something went wrong")
			
			
			print(t) 
			print(myDic)
	sort_dict= dict(sorted(myDic.items(), key=operator.itemgetter(1))) 
	print("Sorted Dictionary by value: ", sort_dict)
	file2 = open('/etc/pacman.d/mirrorlist','w')
    
	for k, v in sort_dict.items():
		print(k)
		try:
			file2.write('Server = '+ k+'\n')
		except:
			print("a problem occured")

	file2.close()
	process="done"
	return process  	
		
		
		
		
# above filters out two ## together 

   
def countryMirrors(someVar):
	# here could put all processing 
    stringOfMirrorsNoHash = ""    
    myDic= {}
    stringOfMirrorsNoHash = re.sub(r'^[##\s]', " ", someVar)
    stringOfMirrorsNoHash2 = re.sub(r'(Server\s=)', "",   stringOfMirrorsNoHash ) 
   
    print(stringOfMirrorsNoHash2)
    
    lines =         stringOfMirrorsNoHash2.splitlines()
    for t in lines:
       try:
             times=(requests.get(t,timeout=3).elapsed.total_seconds())
             myDic[t]=times 
             
       except:
                print ("there is a problem")	
    
    
    print(myDic)
    sort_dict= dict(sorted(myDic.items(), key=operator.itemgetter(1))) 
    print("Sorted Dictionary by value: ", sort_dict)
    file2 = open('/etc/pacman.d/mirrorlist','w')
    
    for k, v in sort_dict.items():
        print(k)
        try:
            file2.write('Server = '+ k+'\n')
        except:
            print("a problem occured")

    file2.close()
    process="done"
    return process   
    
    
def radio_selected():
	t= selected.get()
	print(t)	   
	var.set("waiting")
 
 
def testButtonClicked():
    print('test button cloicked')
    var.set("ok working on it")
   
def countryPicked(event):
	d=countries.get()
	print(d)   
	var.set(' waiting for process button to be clicked')
def _quit():
    root.quit()     
    root.destroy()
    
""" root """   
root = tk.Tk()
root.geometry('500x420')
root.resizable(True,True)
root.title('fetchMirrorsGui')
root.columnconfigure(0,weight=3)
root.columnconfigure(1,weight=1)
root.columnconfigure(2,weight=1)
root.rowconfigure(0,weight=1)
root.rowconfigure(1,weight=1)
root.rowconfigure(2,weight=1)
root.rowconfigure(3,weight=1)
root.rowconfigure(4,weight =1)
root.rowconfigure(5,weight =1)
root.configure(background='LemonChiffon2')
root.option_add("*background", "PaleGoldenrod"),
root.option_add("*foreground", "purple"),




""" style  """


style= ttk.Style()
style.configure('TButton',foreground=[("black")],background=["LightGoldenrod1"])
style.map('TButton', foreground=[('hover', 'black')], background=[('hover', 'LimeGreen')])
style.configure("TCombobox", foreground= "purple", activebackground= "purple",  font=('Helvetica', 14))
style.map('TCombobox', foreground=[('pressed', 'red'), ('active', 'blue')])
style.map('TCombobox', foreground=[('hover', 'red')], background=[('hover', 'yellow')])

style.configure('TCheckbutton',foreground=[("black")],background=["brown"])
style.map('TCheckbutton', foreground=[('hover', 'black')], background=[('hover', 'yellow')])



HighlightFont = font.Font(family='Times', size=12, weight='bold')



topLable = ttk.Label(root, text =""" Radio button 1 for whole mirror list (needs editing to enable) \n
 Radio 2 same but all enabled and .... \n for your Country (or nearest) \n
  click radio button 3 first ..then select a Country from drop down list  \n 
  Then as in all 3  cases click  button to process  """, background='ivory',foreground ="black" , font=HighlightFont)
topLable.grid(column=0,row= 0,columnspan=3)


"""label  next yellow button """

var = tk.StringVar()
var.set('waiting to process')
""" radio 1 label """

l = ttk.Label(root, text ="populate mirror list  and do manual edit to \n activate mirror  you want  (1) -> ", background='LemonChiffon',foreground ="black" )
l.grid(column=0,row=1)

""" radio 1"""
selected = tk.StringVar()
selected.set('2')


""" radio 2 label """

label = ttk.Label(root, text="populate and have all mirrors enabled (2)->", background='LemonChiffon', foreground='black')
label.grid(column=0,row=2)

inform = ttk.Label(root, textvariable =var , background='gray84', foreground='black', font=HighlightFont)
inform.grid(column=0,row=4)



""" radio buttons """
r = ttk.Radiobutton(root,text='1', value='1', variable=selected,command=radio_selected)
r.grid(column=1, row=1 )
s = ttk.Radiobutton(root,text='2', value='2', variable=selected,command=radio_selected)
s.grid(column=1,row=2)
t=  ttk.Radiobutton(root,text='3', value='3', variable=selected,command=radio_selected)
t.grid(column=1, row=3)


"""process button"""

Button1 = ttk.Button(root, text='Process  Above Selection',command=button_clicked)
Button1.grid(column=0,row=5,columnspan=2)







"""  country combobox """


    
countryVar = tk.StringVar()
countries =ttk.Combobox(root, textvariable= countryVar)
countryVar.set("select nearest Country")
countries.grid(column= 0, row =3) 
countries['values']= ('Worldwide','Australia','Austria','Bangladesh' ,'Belarus','Belgium','BosniaNHezegovia',\
 'Brazil', 'Bulgaria', 'Canada','Chile','China','Colombia','Combodia','Croatia','Czechia','Denmark','Ecuador',\
 'Estonia','Finland','France','Georgia','Germany','Greece','HongKong','Hungary','Iceland','India','Indonesia','iran','Ireland',\
 'Israel','Italy','Japan','Kazakhstan', 'Kenya', 'Latvia','Lithuania','Luxembourg','Mexico', 'Moldova','Monaco','Netherlands','NewCaledonia',\
 'NewZealand','North Macedonia','Norway','Pakistan','Paraguay','Poland','Portugal','Romania','Russia','Reunion','Serbia',\
 'Singapore','Slovakia','Slovenia','South Africa','South Korea','Spain','Sweden','Switzerland','Taiwan'\
 'Thailand','Turkey','Ukraine','United Kingdom','USA','Vietnam' )





countries.bind('<<ComboboxSelected>>',countryPicked)


""" testButton 

testButton = ttk.Button(root, text='test event button', command=lambda: button_clicked())
testButton.grid(column=1,row=4)

"""


""" green exit button """

exit_button = ttk.Button(root, text="Exit", command=_quit)
exit_button.grid(column=2,row=5)







root.mainloop()
