include("../WBInclusions")

APFS = "186" # WBCount:APFS
version = APFS

global D = "D = Dict{String, Array{Any}}( # God damn strong typing! [string, string, int?]\n"

pre = "<!DOCTYPE html>\n<html lang=\"en\" dir=\"ltr\">\n<head>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"css/WBmiracle.css\">\n<title>Image inventory</title>\n<meta charset=\"UTF-8\">\n<style>\n    .tar {\n        text-align:right;\n    }\n    .bib {\n        font-weight:bold;\n        color:blue;\n    }\n</style>\n</head>\n<body style=\"background-color:gainsboro;\"><div style=\"padding:2px 0px 0px 6px;\"><a href=\"../welcome.html\" style=\"text-decoration:none;\" class=\"rWel\"><img src=\"images/1/12/Prev2a.gif\" alt=\"Previous\" style=\"padding-left:3px;padding-right:1px;width:10px; height:12px;\">Welcome</a></div>\n<div class=\"read600\">\n"

post = "\n<p style=\"margin-bottom:20px;font-family:monospace;font-size:17px;padding-left:4px;white-space:nowrap;\">XXXX</p>\n<p style=\"margin-bottom:20px;font-family:monospace;font-size:16px;line-height:120%\">XYXY</p>\n<p style=\"margin-top:32px;width:600px;text-align:right;\">[ <a href=\"https://validator.w3.org/\"><span style=\"font-size:larger;vertical-align:-1px;\">&Omega;</span>&nbsp;W3C&nbsp;HTML&nbsp;validator</a> ]</p></div>\n</body></html>"

global unhex = Dict{String,Int32}(
    "0" => 0, "1" => 1, "2" => 2, "3" => 3, "4" => 4, "5" => 5, "6" => 6, "7" => 7,
    "8" => 8, "9" => 9, "a" => 10, "b" => 11, "c" => 12, "d" => 13, "e" => 14, "f" => 15
)

global uppers = Dict{String,Int32}(
    "0" => 0, "1" => 0, "2" => 0, "3" => 0, "4" => 0, "5" => 0, "6" => 0, "7" => 0,
    "8" => 0, "9" => 0, "a" => 0, "b" => 0, "c" => 0, "d" => 0, "e" => 0, "f" => 0
)

global lowers = Dict{String,Int32}(
    "0" => 0, "1" => 0, "2" => 0, "3" => 0, "4" => 0, "5" => 0, "6" => 0, "7" => 0,
    "8" => 0, "9" => 0, "a" => 0, "b" => 0, "c" => 0, "d" => 0, "e" => 0, "f" => 0
)



global ignoreds = [ 
    "JUNK.html",
    "JUNK2.html"
]

global DISTR = Dict(0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0,
    8 => 0, 9 => 0, 10 => 0, 11 => 0, 12 => 0, 13 => 0, 14 => 0, 15 => 0
)
global D10Plus = 0

global distr = []
for i = 1:256
    push!(distr,0)
end

global tbl = Dict()
global maxLen = -1
global ct = 0
global rejects = []
global dshit = []
global FirstImage = true
global REPO = length(ARGS) > 0 && lowercase(ARGS[1]) == "repo"
global TrivialImages = ["Next2a.gif", "Prev2a.gif", "Spacer.gif", "WikiMedia.png"]
global trivials = 0
global Qsum = 0
global Q = ""
global Biggies = []
global TOTSZ = Int64(0)
function qwrite(txt)
    global Qsum += length(txt)
    #write(q, txt)
    global Q *= txt
end

for (root, dirs, files) in walkdir(".")
    #println("Directories in $root")
    #for dir in dirs
    #    println(joinpath(root, dir)) # path to directories
    #end
    #println("Files in $root")
    for file in files
        x = joinpath(root, file) # path to files
        #if !contains(x, "images")
        if findfirst(r"^\.\\images\\([0-9a-f])\\\1[0-9a-f][\\]", x) == nothing
            if findfirst(r"^\.\\(css\\|txts\\|pdfs\\)", x) == nothing
                push!(rejects, x)
            end
            continue
        end
        # Create a directory with copies of all the image files
        if REPO
            tgt = "\\REPO\\" * x[15 : length(x)]
            try                
                rs = open(tgt, "w")
                write(rs, RRead(x, "raw"))
                close(rs)
            catch ex
                s = string(ex)  
                if length(s) > 200
                    s = s[1:200] * "..."
                end
                println("\n      REPO: ", tgt , ": ", typeof(ex), ".\n", s);
            end
        end
        y = length(x)
        z = x[15:y]
        zLen = length(z)
        if zLen > maxLen
            global maxLen = zLen
        end
        global tbl[z] = replace(x[1:14], r"[\\]" => "/")
        global ct += 1
        if !(tbl[z] in dshit)
            push!(dshit, tbl[z])
        end
    end
end
dt = string(Dates.now())
dtx = findfirst('T', dt)
dtx = replace(dt[1: dtx - 1] * " " * dt[dtx + 1: length(dt)], r"\.[0-9]+" => "", count=1)
global stuff = "<p style=\"font-family: sans-serif;color:black;margin-top:24px;margin-bottom:32px;\">&#91;WBCount v" * version * "]&nbsp;&nbsp;" * pwd() * "&nbsp;&nbsp;&nbsp;(--IMAGES--)&nbsp;&nbsp;--S,Z--.<br>maxLen: " * string(maxLen) * ",  count: " *
           string(ct) * ".&nbsp;&nbsp;<span style=\"color:mediumblue;font-weight:bold;background-color:lightyellow;padding:2px 3px 1px 2px;\">" * dtx * "</span>.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"../XXXTree.html\">Links</a>&nbsp;&nbsp;&nbsp;<a href=\"../Dashboard.html\">Dashboard</a><span style=\"vertical-align:1px;padding-left:2px;\"><a href=\"../Dashboard.html\" ><img alt=\"Next2a.gif\" src=\"images/5/5b/Next2a.gif\" width=\"10\" height=\"12\"></a></span><br>"

global stuff *= "<span style=\"font-size:17px;color:darkslategray;\">&#34;Hey,<span style=\"vertical-align:12px;\">&nbsp;</span>don't it always seem to go, that you don't know what you've got 'till it's gone....&#34; (Joni Mitchell; <i>how many pictures I have lost by failing to capture them when I saw them!</i>)</span></p>"

fuck = sort(collect(keys(tbl)), by=lowercase)
global stuff *= "\n<div style=\"height:570px;width:550px; overflow:auto; border: 1px solid black;border-radius:6px;margin:16px 0px 0px 6px;padding:2px 0px 2px 36px;background-color:lightyellow;\"><table style=\"font-family:sans-serif;border-collapse:separate;margin:8px 0px 16px 8px;\">" *
            "<tr><td colspan=3 class=\"tar\">" *
        "<span style=\"border:1px solid black;padding:1px 6px 1px 4px;background-color:white;\">" * 
        "QQsbsQQ" * "</span></td></tr>"
for ks in fuck

    ww = tbl[ks]
    uppers[ww[12:12]] += 1
    lowers[ww[13:13]] += 1
    w = unhex[ww[12:12]] * 16 + unhex[ww[13:13]] + 1
    distr[w] += 1

    # <!-- td><span style=\"padding-left:16px;\">[[File:Next2a.gif|link=Media:" * ks * "|Go to Wiki record for image!]]</span></td -->

#                                                                                       <a href=\"images/" * tbl[ks][10:13] * "/" * ks * "\"</a>                                                                                         
    global stuff *= "<tr><td" * (FirstImage ? " style=\"padding-right:38px;\"" : "") * "><a href=\"images/" * tbl[ks][10:13] * "/" * ks * "\">" * tbl[ks][10:13] * "</a></td><td class=\"bib\">" * ks * 
            "</td><td class=\"tar\">--" * ks * "--</td></tr>\n"
    global FirstImage = false
    # println(tbl[ks], " ",ks)
    global D *= "    \"" * ks * "\" => [\"" * tbl[ks][10:10] * "\", \"" * tbl[ks][12:13] * "\"],\n"
end

for r in rejects
    if r in [".\\WBCount", ".\\WBCount1", ".\\WBKountOut.html", ".\\WBcompare", ".\\WBcompare1"]
        continue
    end
    println("  ", r)
end

println("\n-------")

global ImageCache = Dict{String, Int32}()
global ict = 0
global failures = []
cd("../")                # This shit makes no sense to me, so I cheated. GODDAMNED RIGHT!

try
    for (root, dirs, files) in walkdir("./w/")
        for file in files
            x = joinpath(root, file) # path to files
            if !contains(x, "images")
                continue
            end
            z = replace(x, "\\" => "/")
            global ImageCache[z[3 : length(z)]] = 0
            sz = "       " * string(stat("/ROM/BO/" * z).size)
            sizesz = length(sz)
            push!(Biggies, sz[sizesz - 7:sizesz] * "  " *  z[17:length(z)])
            global ict += 1
        end
    end
    global errId = 1
    a = readdir()
    global errId = 2
    for itm in a
        if findfirst(".html", itm) == nothing || itm in ignoreds
            continue
        end
        global item = itm
        global errId = 4
        txt = RRead(item, "clean")

        txt = replace(txt, r"url\('?([^')]+)'?\)" => s" src=\"\1\" ")  # kludge up backgraound images

        images = findall(r" (src|href)=\"[^\"]+", txt)
        for i = 1 : length(images)
            str0 = txt[images[i]]
            if !contains(str0, "/w/images/")
                if length(str0) >= 10 && str0[1:10] == " href=\"w/i"
                    str0 = replace(str0, " href=\"" => " href=\"./", count = 1)
                elseif length(str0) >= 9 && str0[1:9] == " src=\"w/i"
                    str0 = replace(str0, " src=\"" => " src=\"./", count = 1)
                else
                    continue
                end                
            end
            str1 = replace(str0, "%27" => "'")
            off = findfirst("\"", str0)
            str = str1[(off[1] + 3):length(str1)]

            if haskey(ImageCache, str)
                global ImageCache[str] += 1
            elseif !isfile(str)
                strd = "./" * str[1:13]
                if !isdir(strd)
                    mkdir(strd)
                    println("  ", strd)
                end
                println("?MISSING: ", str)
            else
                println("?GODKNOWSWHAT: ", str)               
            end
        end
    end
    
catch ex
    s = string(ex)  
    if length(s) > 200
        s = s[1:200] * "..."
    end
    println("\n      Failure: ", typeof(ex), ".\n", s);
    #exit(16)
    push!(failures, item)
    return 0
end

global unused = ""
global unusedPfx = ""
global Uct = 0
ks = keys(ImageCache)
global ReverseImages = Dict{Int32, Array{String}}()
global bigsum = 0
global ones = 0
for k in ks
    global TOTSZ += stat(k).size 
    if ImageCache[k] == 0
        global unused *= unusedPfx * "\"" * k * "\""
        global unusedPfx = ", "
        global Uct += 1
    else
        kn = ImageCache[k]
        kkX = k[15:length(k)]

        if k[15:length(k)] in TrivialImages
            global trivials += ImageCache[k]
        end
        global stuff = replace(stuff, "--" * kkX * "--" => string(kn), count=1)
        global bigsum += kn
        if kn == 1
            global ones += 1
        end
        if !(kkX in ["Prev2a.gif", "Next2a.gif", "Spacer.gif", "HTML5V.png", 
                    "GarbageCan.gif", "K2.gif", "Buttocks.jpg", "United_states.gif", "WDSG.gif"]) 
            if haskey(ReverseImages, kn)
                push!(ReverseImages[kn], kkX)  #    ReverseImages[kn] *= ", " * "\"" * kkX * "\""
            else
                global ReverseImages[kn] = [kkX]    #   "\"" * kkX * "\""
            end
        end
    end
end

global tot = 0
print("\nuppers: ")
for z in ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]
    global tot += uppers[z]
    print(" " * string(uppers[z]))
    if z in ["7", "f"]
        print(" " * HI_YELLOW * string(tot) * HI_END * " ")
        global tot = 0
    end
end
println("\n")
global tot = 0 
print("lowers: ")
for z in ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]
    global tot += lowers[z]
    print(" " * string(lowers[z]))
    if z in ["7", "f"]
        print(" " * HI_YELLOW * string(tot) * HI_END * " ")
        global tot = 0
    end
end
println("\n")


print("Going to save ./WBKountOut.html : (" * pwd() * ")\n")
#global q = open("w/WBKountOut.html", "w") #
qwrite(pre)
sbs = formatFixed(bigsum)

consequentials = formatFixed(bigsum - trivials)
stuff = replace(stuff, "--IMAGES--" => "Celibates: " * string(ones))
stuff = replace(stuff, r"<td class=\"tar\">--[^>]+</td>" => "<td class=\"tar\"><span style=\"font-weight:bold;color:crimson;font-size:x-large;font-family:sans-serif;\">**</span></td>")
qt = stuff * "<tr><td colspan=3 class=\"tar\">" *
        "<span style=\"border:1px solid black;padding:1px 6px 1px 4px;background-color:white;\">" * formatFixed(length(ImageCache)) * " &nbsp;<span style=\"font-weight:bold;\">&Sigma;</span><sup><span style=\"padding-left:1px;\">+</span></sup> " * 
        sbs * "</span></td></tr></table></div>"
fuckedup = replace(qt, "QQsbsQQ" => formatFixed(length(ImageCache) - length(TrivialImages)) * " &nbsp;<span style=\"font-weight:bold;\">&Sigma;</span><sup><span style=\"padding-left:1px;\">-</span></sup> " * consequentials, count = 1)
qwrite(fuckedup)

shitx = sort(collect(keys(ReverseImages)), rev=true)
global nuthin = "[nuthin]"
println(" ")
for i = 1 : length(shitx)
    sq = shitx[i]
    if sq < 12             # min usage count for celebities list
        continue
    end
    z = ""
    zzz = sort(ReverseImages[sq])
    for zz in zzz    #   ReverseImages[sq]
        if length(z) > 0
            z *= ", "
        end
        z *= "\"" * zz * "\""      
    end

    s = string(sq)
    u = "(" * string(length(ReverseImages[sq])) * ")      "    
    println(" " ^ (6 - length(s)) * s, " ", u[1:6], z)
    global nuthin = ""
end

if length(unused) > 0
    print("\n    Unused: " * unused * "  (" * string(Uct) * ")\n\n")
    qwrite("<p style=\"margin-top:24px;\">" * replace(replace(unused, "w/images/" => ""), " " => "&nbsp; ") * "</p>")
end

qwrite(post)
#global q = open("w/WBKountOut.html", "w")

Q = replace(Q, "NancyTheBitch.jpg</span></td>" => 
            "NancyTheBitch.jpg</span> (<span style=\"font-style:italic;color:black;vertical-align:-1px;\">~Melva</span>)</td>", count=1)
Q = replace(Q, "FirstSteps.jpg</span></td>" => 
            "FirstSteps.jpg</span> (<span style=\"font-style:italic;color:black;vertical-align:-1px;\">Modified</span>)</td>", count=1)
Q = replace(Q, "Giphy.gif</span></td>" => 
            "Giphy.gif</span> (<span style=\"font-style:italic;color:black;vertical-align:-1px;\">Animated</span>)</td>", count=1)


sQsum = formatFixed(Qsum)
STOTSZ = formatFixed(TOTSZ)

#write(q, replace(Q, "--S,Z--" => "<span style=\"color:gray;\">DDD" * sQsum * "   " * STOTSZ * "</span>", count = 1))
#close(q)
println("\n./WBKountOut.html saved: " * sQsum * "    " * APtS_ET)

if nuthin != ""
    println("    " * nuthin)
end

global shi = []
for s = 1:20
    append!(shi,0)
end

global crap = ""
global crap_HTML = ""
for i = 1 : length(distr)
    if i % 32 == 1
        global crap *= " "
        global crap_HTML *= "&nbsp;"
        if i % 64 == 1
            global crap *= "\n   "
            global crap_HTML *= "<br>"
        end
    end
    distri = distr[i]
    global shi[distri + 1] += 1 
    global crap *= HILITE_TOHEX[distri]
    if distri > 9
        global D10Plus += 1
    end
    DISTR[distri] += 1
    if distri == 0
        global crap_HTML *= "<span style=\"font-weight:bold;color:mediumblue;background-color:ghostwhite;padding:1px 0px 1px 0px;\">.</span>"
    elseif distri < 10
        global crap_HTML *= string(distri)
    else
        global crap_HTML *= "<span style=\"font-weight:bold;color:mediumblue;background-color:ghostwhite;padding:1px 0px 1px 0px;\">" * "ABCDEF"[distri-9:distri-9] * "</span>"
    end
end

global crap_HTML *= "&nbsp;&nbsp;" * string(D10Plus)
 
global mulch = 0
for i = 1: length(shi)
    global mulch += (i - 1) * shi[i]
    if shi[i] != 0
        global shi[i] = [i - 1, shi[i], mulch]
    end
end
for i = 1 : length(shi)
    if shi[length(shi)] != 0
        break
    end
    global shi = copy(shi)[1:length(shi) - 1]
end 

global shidt = 0
global shid = []

for i = 2 : length(shi)
    if shi[i] == 0
        append!(shid, 0)
        continue
    end
    sh = shi[i][2]    #  * (i - 1)
    append!(shid, sh) #  - shi[i - 1][3])
    global shidt += sh
end
tots = []
for itm in shi
    push!(tots, itm[3])
end

#SHID = open("w/SHID", "w")
#write(SHID, "global SHID = " * string(tots))
#close(SHID)
global shidd = []
global dnom = shi[length(shi)][3]
for i = 1 : length(shi)
    push!(shidd, replace(string((shi[i][3]/dnom) * 100 + 0.005) * "0000", r"\.([0-9]{2})[0-9]+" => s".\1") * "%")
end
println(crap * "  " * string(D10Plus) , "\n\n", shi, " ", shidt, "\n\n", replace(string(shidd), "\"" => ""), " " * string(length(shidd) - 1))

global distrBars = ""
for i = 0 : 12
    si = "   " * string(i)
    lensi = length(si)
    si = replace(si[lensi - 2 : lensi], " " => "&nbsp;")
    global distrBars *= si * "   " * ("*" ^ DISTR[i]) * "<br>"
end


Q = replace(Q, "XXXX" => crap_HTML)
Q = replace(Q, "XYXY" => distrBars)

q = open("w/WBKountOut.html", "w")
write(q, replace(Q, "--S,Z--" => "<span style=\"color:gray;\">" * sQsum * "&nbsp; " * STOTSZ * "</span>", count = 1))
close(q)

global D *= ")\n\nglobal DICT_VERSION = \"WBCount v" * version * " (D:001).\"\n\n"
global D *= "global MISSING = [\"MISSING_1\", \"MISSING_2\"]\n\n"
global D *= "function pushD(ky, itm)\n"
global D *= "    r = get!(D, ky, MISSING)\n"
global D *= "    if r == MISSING\n"
global D *= "        return(r)\n"
global D *= "    end\n"                
global D *= "    return(push!(r, itm))\n"
global D *= "end\n\n"
global D *= "function appendD(ky, itm...)\n"
global D *= "    r = get!(D, ky, MISSING)\n"
global D *= "    if r == MISSING\n"
global D *= "        return(r)\n"
global D *= "    end\n"                
global D *= "    return(append!(r, itm...))\n"
global D *= "end\n\n"
global D *= "function getD(ky, ksub)\n"
global D *= "    a = get!(D, ky, MISSING)\n"
global D *= "    if a == MISSING\n"
global D *= "        return(MISSING)\n"
global D *= "    end\n"
global D *= "    if ksub > length(a) || ksub < 1\n"
global D *= "        return(MISSING)\n"
global D *= "    end\n"
global D *= "    return a[ksub]\n"
global D *= "end\n\n"
global D *= "function getD(ky)\n"
global D *= "    return(get!(D, ky, MISSING))\n"
global D *= "end\n\n"
global D *= "global DCOLOR1 = HI_RED * \"****** \"\n"
global D *= "global DCOLOR2 = HI_END\n"
global D *= "function addD(ky, val)\n"
global D *= "    if typeof(val) != Vector{String} || length(val) != 2 || typeof(val[1]) != String ||\n"
global D *= "                typeof(val[2]) != String\n"
global D *= "        throw(ArgumentError(DCOLOR1 * \"Bad argument: \" * string(val) * DCOLOR2))\n"
global D *= "    end\n"
global D *= "    if typeof(ky) != String\n"
global D *= "        throw(ArgumentError(DCOLOR1 * \"Bad key: \" * string(ky) * DCOLOR2))\n"
global D *= "    end\n"
global D *= "    if getD(ky) != MISSING\n"
global D *= "        throw(ArgumentError(DCOLOR1 * \"Exists: \" * string(ky) * DCOLOR2))\n"
global D *= "    end\n"
global D *= "    D[ky] = val\n"
global D *= "    return(D[ky])\n"
global D *= "end\n"

d = pwd() * "\\w\\DICT"
a = open(d, "w")
write(a, D)
close(a)

a = open("w/BIG", "w")
b = sort(Biggies, rev=true)[1:24]
for c in b
    write(a, c * "\n")
end
close(a)
