import pywikibot
import re
from pywikibot import pagegenerators
import unicodedata
regexlist = {
    "m":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|( ))*(m)",
    "ft":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|( ))*(ft)",
    "in":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|( ))*(in)",
    "sqm":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(sqm|m2|ft<sup>2<\/sup>|m²)",
    "sqft":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*({{nowrap\|sq ft}}|sqft|ft2|ft<sup>2<\/sup>|ft²)",
    "kg":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(kg)",
    "lb":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(lb)",
    "kw":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(kw|kW)",
    "hp":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(hp|\[\[horsepower\|hp]])",
    "shp":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(shp|\[\[horsepower\|shp]])",
    "kn":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(kn|kN|\[\[kilonewton\|kN]])",
    "lbf":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(\[\[pound-force\|lb<sub>f<\/sub>]]|lbf|\[\[pound-force\|lbf]])",
    "kmh":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(kmh|km\/h)",
    "mph":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑][½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(mph)",
    "kts":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(kts|kt|knots|\[\[knot \(unit\)\|knots]])",
    "mach":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(mach)",
    "km":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(km)",
    "miles":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(miles|mi)",
    "nmi":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(nmi|\[\[nautical mile\|nmi]]|nm)",
    "ms":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(ms|m\/s)",
    "ftmin":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(ftmin|ft\/min)",
    "kg/m2":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(kg/m²|kg\/m2|kg\/m<sup>2<\/sup>)",
    "lb/sqft":"([0-9\.\,]+)([½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑])?(\+)?([\s\.\,]|(&nbsp;))*(lb\/sqft|lb/ft²|lb\/ft<sup>2<\/sup>)"  
}
def unitparam(unit,main): 
    if ((x[1].get(main+" main") is not "") and (main+" main" in x[1].keys())) or ((x[1].get(main+" alt") is not "") and (main + " alt" in x[1].keys())):
        if x[1].get(main):
            if re.search(regexlist.get(unit),x[1].get(main+" main")):
                fraction = 0
                if re.search(regexlist.get(unit),x[1].get(main+" main")).group(2) is not None:
                    fraction = unicodedata.numeric(re.search(regexlist.get(unit),x[1].get(main+" main")).group(2))
                    return str(int(re.search(regexlist.get(unit),x[1].get(main+" main")).group(1).replace(",",""))+fraction)
                return re.search(regexlist.get(unit),x[1].get(main+" main")).group(1).replace(",","")
            elif re.search(regexlist.get(unit),x[1].get(alt)):
                fraction = 0
                if re.search(regexlist.get(unit),x[1].get(main+" alt")).group(2) is not None:
                    fraction = unicodedata.numeric(re.search(regexlist.get(unit),x[1].get(main+" alt")).group(2))
                    return str(int(re.search(regexlist.get(unit),x[1].get(alt)).group(1).replace(",",""))+fraction)
                return re.search(regexlist.get(unit),x[1].get(main+" alt")).group(1).replace(",","")
            elif unit == "in" and (re.search(regexlist.get("ft"),x[1].get(main)) or re.search(regexlist.get("ft"),x[1].get(main+" alt"))):
                return "0"
            if unit == "mach" or unit == "shp" or unit == "hp":
                return ""
            else:
                errorpage.text += "\n*Unidentified unit at " 
                errorpage.text += page.full_url()
                errorpage.text += " " 
                errorpage.text += x[1].get(main)
                errorpage.text += ", " 
                errorpage.text += x[1].get(alt)
                errorpage.text += "Looking for: " 
                errorpage.text += unit
                errorpage.save("Added unidentified unit problem")
                
                if unit == "mach" or unit == "shp" or unit == "hp" or unit == "kts":
                    return ""
                return ""
                abort=True
    else: 
        return ""
def unitif(what, unit, main, alt):
    if what:
        return unitparam(unit, main, alt)
    else:
        return ""
def findtype(what,x):
    if x.get("plane or copter?") == "plane" and what == "plane":
        return True
    if x.get("plane or copter?") == "copter" and what == "copter":
        return True
    if not (x.get("plane or copter?") == "copter" or x.get("plane or copter?") == "plane"):
        errorpage.text += "*Unknown type at " 
        errorpage.text += page.full_url()
        errorpage.save("Added unknown type problem")
        abort=True
    if (x.get("plane or copter?") == "copter" and what == "plane") or (x.get("plane or copter?") == "plane" and what == "copter"):
        return False
def findprimeunit(x):
    if re.search(regexlist["m"],x.get("length main")) and re.search(regexlist["ft"],x.get("length alt")):
        return "met"
    elif re.search(regexlist["ft"],x.get("length main")) and re.search(regexlist["m"],x.get("length alt")):
        return "imp"
    else:
        errorpage.text += "*Unknown prime unit at " 
        errorpage.text += page.full_url()
        errorpage.save("Added primeunit problem")
        abort=True
def get(x,index,note=False):
    if (x.get(index) is not "") and (index in x.keys()):
        if note:
            return "*" + x.get(index)
        return x.get(index)
    else: 
        return ""
def unitfail(unitlist)
def armaments():
    if(x[1].get("armaments") is "") or ("armaments" not in x[1].keys()):
        return("")
    elif (x[1].get("armaments") is not "") and ("armaments" in x[1].keys()):
        return """|armament = """ + get(x,"armament") + """<!-- add bulletted list here or if you want to use the following 
        specific parameters, remove this parameter--> """
    else:
        abort = True
        errorpage.text += "*Armaments error at " 
        errorpage.text += page.full_url()
        errorpage.save("Added amements error")
def badparam():
     if ((x[1].get("number of propellers per engine") is not "") and ("number of propellers per engine" in x[1].keys())) or ((x[1].get("useful load main") is not "") and ("useful load main" in x[1].keys())):
        abort = True
        errorpage.text += "*Bad parameter at " 
        errorpage.text += page.full_url()
        errorpage.save("Added bad parameter problem")
def payload():
    payloadtext = ""
    if(((x[1].get("payload main") is not "") and ("payload main" in x[1].keys()))):
        payloadtext = payloadtext + "\n**" + get(x[1],"payload main") + " (" + get(x[1],"payload alt") + ")"
    if(((x[1].get("payload more") is not "") and ("payload more" in x[1].keys()))):
        payloadtext = payloadtext + "\n" + get(x[1],"payload more")
    return payloadtext
def powermass():
    powermasstext = ""
    if(((x[1].get("power/mass main") is not "") and ("power/mass main" in x[1].keys()))):
        powermasstext = powermasstext + get(x[1],"power/mass main")
        if(((x[1].get("power/mass alt") is not "") and ("power/mass alt" in x[1].keys()))):
            powermasstext = powermasstext + " (" + get(x[1],"payload more")+ ")"
    return powermasstext
def draw(x):
    longtext = ("""{{Aircraft specs
    |ref                        = <!-- reference --> """ + get(x,"ref") + """
    |prime units?               = """ + primeunit + """
    <!-- imp or kts first for US aircraft, and UK aircraft pre-metrification, 
    met(ric) first for all others. You MUST choose a format, or no specifications will show -->
    <!--General characteristics-->
    |crew                   = """ + get(x,"crew") + """
    |capacity               = """ + get(x,"capacity") + payload() + """
    |length m               = """ + unitparam("m","length") + """
    |length ft              = """ + unitparam("ft","length") + """
    |length in              = """ + unitparam("in","length") + """
    |span m                 = """ + unitif(plane,"m","span") + """
    |span ft                = """ + unitif(plane,"ft","span") + """
    |span in                = """ + unitif(plane,"in","span") + """
    |height m               = """ + unitparam("m","height") + """
    |height ft              = """ + unitparam("ft","height") + """
    |height in              = """ + unitparam("in","height") + """
    |wing area sqm          = """ + unitif(plane,"sqm","area") + """
    |wing area sqft         = """ + unitif(plane,"sqft","area") + """
    |aspect ratio           = """ + get(x,"aspect ratio") + """
    |airfoil                = """ + get(x,"airfoil") + """
    |empty weight kg        = """ + unitparam("kg","empty weight") + """
    |empty weight lb        = """ + unitparam("lb","empty weight") + """
    |gross weight kg        = """ + unitparam("kg","loaded weight") + """
    |gross weight lb        = """ + unitparam("lb","loaded weight") + """
    |max takeoff weight kg  = """ + unitparam("kg","max takeoff weight") + """
    |max takeoff weight lb  = """ + unitparam("lb","max takeoff weight") + """
    |more general           = """ + get(x,"more general", True) + """
    <!--Powerplant-->
    |eng1 number            = """ + get(x,"number of props") + get(x,"number of jets") + """
    |eng1 name              = """ + get(x,"engine (prop)") + get(x,"engine (jet)") + """
    |eng1 type              = """ + get(x,"type of prop") + get(x,"type of jet") + """
    |eng1 kw                = <!-- prop engines --> """ + unitparam("kw","power") + """
    |eng1 hp                = <!-- prop engines --> """ + unitparam("hp","power") + """
    |eng1 shp               = <!-- prop engines --> """ + unitparam("shp","power") + """
    |eng1 kn                = <!-- jet/rocket engines --> """ + unitparam("kn","thrust") + """
    |eng1 lbf               = <!-- jet/rocket engines --> """ + unitparam("lbf","thrust") + """
    |power original         = """ + get(x,"power original") + """
    |thrust original        = """ + get(x,"thrust original") + """
    |eng1 kn-ab             = """ + unitparam("kn","afterburning thrust") + """
    |eng1 lbf-ab            = """ + unitparam("lbf","afterburning thrust") + """
    |more power             = """ + get(x,"more general powerplant", True) + """
    |prop name              = """ + get(x,"propellers") + """
    |prop dia m             = <!-- propeller aircraft --> """ + unitparam("m","propeller diameter") + """
    |prop dia ft            = <!-- propeller aircraft --> """ + unitparam("ft","propeller diameter") + """
    |prop dia in            = <!-- propeller aircraft --> """ + unitparam("in","propeller diameter") + """
    |rot dia m              = <!-- helicopters --> """ + unitif(copter,"m","span main") + """
    |rot dia ft             = <!-- helicopters --> """ + unitif(copter,"ft","span main") + """
    |rot dia in             = <!-- helicopters --> """ + unitif(copter,"in","span main")  + """
    |rot area sqm           = <!-- helicopters --> """ + unitif(copter,"sqm","area")  + """
    |rot area sqft          = <!-- helicopters --> """ + unitif(copter,"sqft","area") + """
    <!--Performance-->
    |max speed kmh          = """ + unitparam("kmh","max speed") + """
    |max speed mph          = """ + unitparam("mph","max speed") + """
    |max speed kts          = """ + unitparam("kts","max speed") + """
    |max speed note         = """ + get(x,"max speed more") + """
    |max speed mach         = """ + unitparam("mach","max speed") + """
    |cruise speed kmh       = """ + unitparam("kmh","cruise speed") + """
    |cruise speed mph       = """ + unitparam("mph","cruise speed") + """
    |cruise speed kts       = """ + unitparam("kts","cruise speed") + """
    |cruise speed note      = """ + get(x,"cruise speed more") + """
    |stall speed kmh        = """ + unitparam("kmh","stall speed") + """
    |stall speed mph        = """ + unitparam("mph","stall speed") + """
    |stall speed kts        = """ + unitparam("kts","stall speed") + """
    |stall speed note       = """ + get(x,"stall speed more") + """
    |never exceed speed kmh = """ + unitparam("kmh","never exceed speed") + """
    |never exceed speed mph = """ + unitparam("mph","never exceed speed") + """
    |never exceed speed kts = """ + unitparam("kts","never exceed speed") + """
    |range km               = """ + unitparam("km","range") + """
    |range miles            = """ + unitparam("miles","range") + """
    |range nmi              = """ + unitparam("nmi","range") + """
    |range note             = """ + get(x,"range more") + """
    |combat range km        = """ + unitparam("km","combat radius") + """
    |combat range miles     = """ + unitparam("miles","combat radius") + """
    |combat range nmi       = """ + unitparam("nmi","combat radius") + """
    |combat range note      = """ + get(x,"combat radius more") + """
    |ferry range km         = """ + unitparam("km","ferry range") + """
    |ferry range miles      = """ + unitparam("miles","ferry range") + """
    |ferry range nmi        = """ + unitparam("nmi","ferry range") + """
    |ferry range note       = """ + get(x,"ferry range more") + """
    |endurance              = <!-- if range unknown --> """ + get(x,"endurance") + """
    |ceiling m              = """ + unitparam("m","ceiling") + """
    |ceiling ft             = """ + unitparam("ft","ceiling") + """
    |ceiling note           = """ + get(x,"ceiling more") + """
    |climb rate ms          = """ + unitparam("ms","climb rate") + """
    |climb rate ftmin       = """ + unitparam("ftmin","climb rate") + """
    |climb rate note        = """ + get(x,"climb rate more") + """
    |sink rate ms           = <!-- sailplanes --> """ + unitparam("ms","sink rate") + """
    |sink rate ftmin        = <!-- sailplanes --> """ + unitparam("ftmin","sink rate") + """
    |sink rate note         = """ + get(x,"sink rate more") + """
    |wing loading kg/m2     = """ + unitif(plane,"kg/m2","loading") + """
    |wing loading lb/sqft   = """ + unitif(plane,"lb/sqft","loading") + """
    |disk loading kg/m2     = """ + unitif(copter,"kg/m2","loading") + """
    |disk loading lb/sqft   = """ + unitif(copter,"lb/sqft","loading") + """
    |power/mass             = """ + powermass() + """
    |thrust/weight          = """ + get(x,"thrust/weight") + """
    |more performance       = """ + get(x,"more performance", True) + """
    <!--Armament-->
    """ + armaments() + """
    |guns                   = """ + get(x,"guns") + """
    |bombs                  = """ + get(x,"bombs") + """
    |rockets                = """ + get(x,"rockets") + """
    |missiles               = """ + get(x,"missiles") + """
    |hardpoints             = """ + get(x,"hardpoints")+ """
    |hardpoint capacity     = """ + get(x,"hardpoint capacity") + """
    |hardpoint rockets      = """ + get(x,"hardpoint rockets") + """
    |hardpoint missiles     = """ + get(x,"hardpoint missiles") + """
    |hardpoint bombs        = """ + get(x,"hardpoint bombs") + """
    |hardpoint other        = """ + get(x,"hardpoint other") + """
    |avionics               = """ + get(x,"avionics") + "}}")
    return longtext
site = pywikibot.Site('en', 'wikipedia')
errorpage = pywikibot.Page(site, u"User:PearBOT/Aircraft specs problems")
oldpage = pywikibot.Page(site, u"User:PearBOT/test")
for page in pywikibot.pagegenerators.PrefixingPageGenerator("User:PearBOT/test"):
    text = page.text
    templates=pywikibot.textlib.extract_templates_and_params(text,remove_disabled_parts="yes",strip = "yes")
    for x in templates:
        print(x[0])
        if x[0] == "Aircraft specifications" or x[0] =="Aircraft specification" or x[0] == "Airtemp-test" or x[0] == "Airtemp-test" or x[0] == "aircraft specifications" or x[0] =="aircraft specification" or x[0] == "airtemp-test" or x[0] == "airtemp-test":       
            longtext=""
            abort = False
            plane = False
            copter = False
            copter=findtype("copter", x[1]);
            plane=findtype("plane", x[1]);
            print("Copter:"+str(copter)+"Plane:"+str(plane))
            primeunit=findprimeunit(x[1]);
            print(primeunit)
            templatetext=draw(x[1]);
            if abort is False:
                page.text = templatetext
                page.save(u"Bot test")
VERBOSE:pywiki:Found 1 wikipedia:en processes running, including this one.
Aircraft specs
cite web
aircraft specifications
Copter:FalsePlane:True
imp
Page [[User:PearBOT/Aircraft specs problems]] saved
INFO:pywiki:Page [[User:PearBOT/Aircraft specs problems]] saved
Sleeping for 9.6 seconds, 2019-08-06 23:10:09
INFO:pywiki:Sleeping for 9.6 seconds, 2019-08-06 23:10:09
Page [[User:PearBOT/Aircraft specs problems]] saved
INFO:pywiki:Page [[User:PearBOT/Aircraft specs problems]] saved
Sleeping for 9.6 seconds, 2019-08-06 23:10:20
INFO:pywiki:Sleeping for 9.6 seconds, 2019-08-06 23:10:20
Page [[User:PearBOT/Aircraft specs problems]] saved
INFO:pywiki:Page [[User:PearBOT/Aircraft specs problems]] saved
Sleeping for 9.6 seconds, 2019-08-06 23:10:30
INFO:pywiki:Sleeping for 9.6 seconds, 2019-08-06 23:10:30
Page [[User:PearBOT/test2]] saved
INFO:pywiki:Page [[User:PearBOT/test2]] saved
Sleeping for 9.2 seconds, 2019-08-06 23:10:40
INFO:pywiki:Sleeping for 9.2 seconds, 2019-08-06 23:10:40
aircraft specifications
Copter:FalsePlane:True
imp
Page [[User:PearBOT/test3]] saved
INFO:pywiki:Page [[User:PearBOT/test3]] saved
nowrap
aircraft specifications
Copter:FalsePlane:True
imp
Sleeping for 9.4 seconds, 2019-08-06 23:10:50
INFO:pywiki:Sleeping for 9.4 seconds, 2019-08-06 23:10:50
Page [[User:PearBOT/Aircraft specs problems]] saved
INFO:pywiki:Page [[User:PearBOT/Aircraft specs problems]] saved
Sleeping for 9.6 seconds, 2019-08-06 23:11:00
INFO:pywiki:Sleeping for 9.6 seconds, 2019-08-06 23:11:00
Page [[User:PearBOT/Aircraft specs problems]] saved
INFO:pywiki:Page [[User:PearBOT/Aircraft specs problems]] saved
Sleeping for 9.5 seconds, 2019-08-06 23:11:10
INFO:pywiki:Sleeping for 9.5 seconds, 2019-08-06 23:11:10
Page [[User:PearBOT/test4]] saved
INFO:pywiki:Page [[User:PearBOT/test4]] saved
Sleeping for 9.3 seconds, 2019-08-06 23:11:20
INFO:pywiki:Sleeping for 9.3 seconds, 2019-08-06 23:11:20
Aircraft specifications
Copter:FalsePlane:True
imp
Page [[User:PearBOT/Aircraft specs problems]] saved
INFO:pywiki:Page [[User:PearBOT/Aircraft specs problems]] saved
Sleeping for 9.5 seconds, 2019-08-06 23:11:30
INFO:pywiki:Sleeping for 9.5 seconds, 2019-08-06 23:11:30
Page [[User:PearBOT/Aircraft specs problems]] saved
INFO:pywiki:Page [[User:PearBOT/Aircraft specs problems]] saved
Sleeping for 9.6 seconds, 2019-08-06 23:11:40
INFO:pywiki:Sleeping for 9.6 seconds, 2019-08-06 23:11:40
Page [[User:PearBOT/Aircraft specs problems]] saved
INFO:pywiki:Page [[User:PearBOT/Aircraft specs problems]] saved
Sleeping for 9.5 seconds, 2019-08-06 23:11:50
INFO:pywiki:Sleeping for 9.5 seconds, 2019-08-06 23:11:50
Page [[User:PearBOT/Aircraft specs problems]] saved
INFO:pywiki:Page [[User:PearBOT/Aircraft specs problems]] saved
Sleeping for 9.6 seconds, 2019-08-06 23:12:00
INFO:pywiki:Sleeping for 9.6 seconds, 2019-08-06 23:12:00
Page [[User:PearBOT/test5]] saved
INFO:pywiki:Page [[User:PearBOT/test5]] saved
Convert
Convert
cvt