class KanjiGridAuto:
    def __init__(self, mw):
        if mw:
            self.menuAction = QAction("Generate Kanji Grid Automatic", mw)
            self.menuAction.triggered.connect(self.setup)
            mw.form.menuTools.addSeparator()
            mw.form.menuTools.addAction(self.menuAction)

    def generate(self, units, timeNow, autoModTime, saveMode=False):
        #deckname = mw.col.decks.name(self.did).rsplit('::',1)[-1]
        if saveMode: cols = _wide
        else: cols = _thin
        self.html = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n"
        self.html += "<html><head><title>Anki Kanji Grid</title></head><body bgcolor=\"#FFF\">\n"
        #self.html += "<span style=\"font-size: 3em;color: #888;\">Kanji Grid - %s</span><br>\n" % deckname
        self.html += "<span style=\"font-size: 3em;color: #888;\">Kanji Grid - " + autoModTime + "</span><br>\n"
        self.html += "<div style=\"margin-bottom: 24pt;padding: 20pt;\"><p style=\"float: left\">Key:</p>"
        self.html += "<style type=\"text/css\">table {font-size:16px; font-family:meiryo;}" + \
            ".key{display:inline-block;width:3em;}a,a:visited{color:#000;text-decoration:none;}</style>"
        self.html += "<p style=\"float: right\">Weak&nbsp;"
        for c in [n / 6.0 for n in range(6 + 1)]:
            self.html += "<span class=\"key\" style=\"background-color: %s;\">&nbsp;</span>" % hsvrgbstr(
                c / 2)
        self.html += "&nbsp;Strong</p></div>\n"
        self.html += "<div style=\"clear: both;\"><br><hr style=\"border-style: dashed;border-color: #666;width: 60%;\"><br></div>\n"
        self.html += "<center>\n"
        if _group in (0, 1, 2):
            if _group == 0:
                _grades = _jlpt
            elif _group == 1:
                _grades = _jouyou
            elif _group == 2:
                _grades = _kanken
            gc = 0
            kanji = list([u.value for u in list(units.values())])
            for i in range(1, len(_grades)):
                self.html += "<h2 style=\"color:#888;\">%s Kanji</h2>\n" % _grades[
                    i][0]
                table = "<table width='85%'><tr>\n"
                count = -1
                for unit in [units[c] for c in _grades[i][1] if c in kanji]:
                    if unit.count != 0 or _unseen:
                        score = "NaN"
                        count += 1
                        if count % cols == 0 and count != 0:
                            table += "</tr>\n<tr>\n"
                        if unit.count != 0:
                            bgcolour = hsvrgbstr(
                                scoreAdjust(unit.avg_interval / _interval) / 2)
                        else:
                            bgcolour = "#FFF"
                        if _tooltips:
                            tooltip = "Character: %s | Count: %s | " % (
                                unicodedata.name(unit.value), unit.count)
                            tooltip += "Avg Interval: %s | Score: %s | " % (
                                unit.avg_interval, score)
                            tooltip += "Background: %s | Index: %s" % (
                                bgcolour, count)
                            table += "\t<td align=center valign=top style=\"background:%s;\" title=\"%s\">" % (
                                bgcolour, tooltip)
                        else:
                            table += "\t<td align=center valign=top style=\"background:%s;\">" % (
                                bgcolour)
                        table += "<a href=\"http://jisho.org/kanji/details/%s\">%s</a></td>\n" % (
                            2 * (unit.value, ))
                table += "</tr></table>\n"
                n = count + 1
                t = len(_grades[i][1])
                gc += n
                if _unseen:
                    table += "<details><summary>Missing kanji</summary><table style=\"max-width:75%;\"><tr>\n"
                    count = -1
                    for char in [c for c in _grades[i][1] if c not in kanji]:
                        score = "NaN"
                        count += 1
                        if count % cols == 0: table += "</tr>\n<tr>\n"
                        if _tooltips:
                            tooltip = "Character: %s" % (
                                unicodedata.name(char))
                            table += "\t<td align=center valign=top style=\"background:#EEE;color:#FFF;\" title=\"%s\">" % (
                                tooltip)
                        else:
                            table += "\t<td align=center valign=top style=\"background:#EEE;color:#FFF;\">"
                        table += "<a href=\"http://jisho.org/kanji/details/%s\" style=\"color:#888;\">%s</a></td>\n" % (
                            2 * (char, ))
                    if count == -1:
                        table += "<strong style=\"color:#CCC\">None</strong>"
                    table += "</tr></table></details>\n"
                self.html += "<h4 style=\"color:#888;\">%d of %d - %0.2f%%</h4>\n" % (
                    n, t, n * 100.0 / t)
                self.html += table

            chars = reduce(lambda x, y: x + y, list(dict(_grades).values()))
            self.html += "<h2 style=\"color:#888;\">%s Kanji</h2>" % _grades[
                0][0]
            table = "<table width='85%'><tr>\n"
            count = -1
            for unit in [
                    u for u in list(units.values()) if u.value not in chars
            ]:
                if unit.count != 0 or _unseen:
                    score = "NaN"
                    count += 1
                    if count % cols == 0 and count != 0:
                        table += "</tr>\n<tr>\n"
                    if unit.count != 0:
                        bgcolour = hsvrgbstr(
                            scoreAdjust(unit.avg_interval / _interval) / 2)
                    else:
                        bgcolour = "#FFF"
                    if _tooltips:
                        tooltip = "Character: %s | Count: %s | " % (
                            unicodedata.name(unit.value), unit.count)
                        tooltip += "Avg Interval: %s | Score: %s | " % (
                            unit.avg_interval, score)
                        tooltip += "Background: %s | Index: %s" % (bgcolour,
                                                                   count)
                        table += "\t<td align=center valign=top style=\"background:%s;\" title=\"%s\">" % (
                            bgcolour, tooltip)
                    else:
                        table += "\t<td align=center valign=top style=\"background:%s;\">" % (
                            bgcolour)
                    table += "<a href=\"http://www.csse.monash.edu.au/~jwb/cgi-bin/wwwjdic.cgi?1MMJ%s\">%s</a></td>\n" % (
                        2 * (unit.value, ))
            table += "</tr></table>\n"
            n = count + 1
            self.html += "<h4 style=\"color:#888;\">%d of %d - %0.2f%%</h4>\n" % (
                n, gc, 0 if gc == 0 else n * 100.0 / gc)
            self.html += table
        else:
            table = "<table width='85%'><tr>\n"
            if _group == 3:  # Order found
                unitsList = sorted(list(units.values()),
                                   key=lambda unit: (unit.idx, unit.count))
            if _group == 4:  # Unicode index
                unitsList = sorted(list(units.values()),
                                   key=lambda unit:
                                   (unicodedata.name(unit.value), unit.count))
            if _group == 5:  # Character score
                unitsList = sorted(
                    list(units.values()),
                    key=lambda unit:
                    (scoreAdjust(unit.avg_interval / _interval), unit.count),
                    reverse=True)
            if _group == 6:  # Deck frequency
                unitsList = sorted(
                    list(units.values()),
                    key=lambda unit:
                    (unit.count, scoreAdjust(unit.avg_interval / _interval)),
                    reverse=True)
            count = -1
            for unit in unitsList:
                if unit.count != 0 or _unseen:
                    score = "NaN"
                    count += 1
                    if count % cols == 0 and count != 0:
                        table += "</tr>\n<tr>\n"
                    if unit.count != 0:
                        bgcolour = hsvrgbstr(
                            scoreAdjust(unit.avg_interval / _interval) / 2)
                    else:
                        bgcolour = "#FFF"
                    if _tooltips:
                        tooltip = "Character: %s | Count: %s | " % (
                            unicodedata.name(unit.value), unit.count)
                        tooltip += "Avg Interval: %s | Score: %s | " % (
                            unit.avg_interval, score)
                        tooltip += "Background: %s | Index: %s" % (bgcolour,
                                                                   count)
                        table += "\t<td align=center valign=top style=\"background:%s;\" title=\"%s\">" % (
                            bgcolour, tooltip)
                    else:
                        table += "\t<td align=center valign=top style=\"background:%s;\">" % (
                            bgcolour)
                    table += "<a href=\"http://www.csse.monash.edu.au/~jwb/cgi-bin/wwwjdic.cgi?1MMJ%s\">%s</a></td>\n" % (
                        2 * (unit.value, ))
            table += "</tr></table>\n"
            self.html += "<h4 style=\"color:#888;\">%d total unique kanji</h4>\n" % (
                count + 1)
            self.html += table
        self.html += "</center></body></html>\n"

    def displaygrid(self, units, timeNow):
        autoModTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        currentTimeTemp = autoModTime.replace(":", "")
        currentTime = currentTimeTemp.replace(" ", "-")

        self.generate(units, timeNow, autoModTime)
        self.win = QDialog(mw)
        self.wv = AnkiWebView()
        self.wv.setHtml(self.html)
        self.wv.show()
        #self.savepng(currentTime)
        return 0

    def savepng(self, currentTime):
        global _filePathBase

        mw.progress.start(immediate=True)

        folder = ""
        if _group == 0:
            folder = "Sorted_by_jlpt/"
        elif _group == 1:
            folder = "Sorted_by_jouyou/"
        elif _group == 2:
            folder = "Sorted_by_kanken/"
        elif _group == 3:
            folder = "Sorted_by_order_found/"
        elif _group == 4:
            folder = "Sorted_by_unicode/"
        elif _group == 5:
            folder = "Sorted_by_score/"
        elif _group == 6:
            folder = "Sorted_by_frequency_in_decks/"

        if (_filePathBase[-1:]) != "/": _filePathBase += "/"
        filePath = _filePathBase + folder

        if not os.path.exists(filePath):
            os.makedirs(filePath)

        fileName = filePath + currentTime + ".png"

        image = QImage(self.wv.size(), QImage.Format_ARGB32)

        #Actually make/render the image
        painter = QPainter(image)
        self.wv.render(painter)
        painter.end()

        image.save(fileName, "png")

        mw.progress.finish()
        return

    def kanjigridAuto(self):
        #self.did = mw.col.conf['curDeck']

        #dids = [self.did]
        #for name, id in mw.col.decks.children(self.did):
        #dids.append(id)
        #cids = mw.col.db.list("select id from cards where did in %s or odid in %s" % (ids2str(dids),ids2str(dids)))
        cids = mw.col.db.list("select id from cards")

        units = dict()
        notes = dict()
        timeNow = time.time()
        for id, i in enumerate(cids):
            card = mw.col.getCard(i)
            if card.nid not in list(notes.keys()):
                keys = list(card.note().keys())
                unitKey = None
                matches = None
                if _literal:
                    matches = operator.eq
                else:
                    matches = operator.contains
                for keyword in _pattern:
                    for s, key in ((key.lower(), key) for key in keys):
                        if matches(s.lower(), keyword):
                            unitKey = card.note()[key]
                            break
                notes[card.nid] = unitKey
            else:
                unitKey = notes[card.nid]
            if unitKey != None:
                for ch in unitKey:
                    addUnitData(units, ch, i, card, timeNow)
        return units, timeNow

    def makegrid(self):
        global _group
        (units, timeNow) = self.kanjigridAuto()
        howManySorts = len(_chosenSortingMethods)
        for i in range(howManySorts):
            _group = _sortingMethods.index(
                _chosenSortingMethods[i]
            )  #Only sets group equal to the index of the chosen sorting methods
            if units is not None:
                self.displaygrid(units, timeNow)

    def setup(self):
        global _pattern, _literal
        global _interval, _thin, _wide
        global _group, _unseen, _tooltips
        swin = QDialog(mw)
        #_pattern = _pattern.lower() #all fields are made lowercase before checking, so this should be lowercase too
        for i in range(len(_pattern)):
            _pattern[i] = _pattern[i].lower()
        mw.progress.start(immediate=True)
        #_pattern = field.text().lower().split()
        self.makegrid()
        mw.progress.finish()