#! /usr/bin/env python3

import ctags
from ctags import CTags, TagEntry
import sys
from icecream import ic
import shutil
from . import config


def loadTagFile(path='.vimwiki_tags'):
    # Available file information keys:
    #  opened -  was the tag file successfully opened?
    #  error_number - errno value when 'opened' is false
    #  format - format of tag file (1 = original, 2 = extended)
    #  sort - how is the tag file sorted?
    #  author - name of author of generating program (may be empy string)
    #  name - name of program (may be empy string)
    #  url - URL of distribution (may be empy string)
    #  version - program version (may be empty string)
    try:
        tagFile = CTags(path)
        return tagFile
    except:
        print("No tagfile at {}".farmat(path))
        sys.exit(1)


def loopThrough(tagFile):
    # Available TagEntry keys:
    #  name - name of tag
    #  file - path of source file containing definition of tag
    #  pattern - pattern for locating source line (None if no pattern)
    #  lineNumber - line number in source file of tag definition (may be zero if not known)
    #  kind - kind of tag (none if not known)
    #  fileScope - is tag of file-limited scope?

    # Note: other keys will be assumed as an extension key and will
    # return None if no such key is found
    ''' Entries that are less than 1 character in length are errors
        Returns a set containing of all the files with errors in their tags'''
    entry = TagEntry()
    tag = tagFile.next(entry)
    tagErrors = set()
    errorTagNames = set()
    while tag:
        if len(entry['name']) <= 1:
            tagErrors.add(entry['file'])
            errorTagNames.add(entry['name'])
        else:
            print("Good tag found: {}".format(entry['name']))
        tag = tagFile.next(entry)
    ic(errorTagNames)
    return tagErrors


def fixErrors(errors):
    ''' Replaces :: with :, which seems to be the error for many of the tags '''
    fileBase = config.files_folder
    for v in errors:
        print("Fixing {}...".format(v))
        fileName = fileBase + getFileName(v)
        newFile = ""
        with open(fileName, 'r') as f:
            for line in f.readlines():
                line = line.replace("::", ":")
                newFile = newFile + line
        with open(fileName, 'w') as f:
            for line in newFile:
                f.write(line)
        print("Written new file...")
        print()
        print(newFile)


def printErrors(errors):
    fileBase = config.files_folder
    for v in errors:
        fileName = fileBase + getFileName(v)
        print("Reading {}...".format(v))
        with open(fileName, 'r') as f:
            f.readline()
            ic(f.readline())


def getFileName(f):
    return str(f, encoding="utf-8")


def getBackupFiles(errors):
    fileBase = config.files_folder
    backupBase = config.files_folder + '/jrnl/'
    for files in errors.values():
        for f in files:
            f = getFileName(f)
            print("Moving {} from backup".format(f))
            shutil.copy(backupBase + f, fileBase + f)


if __name__ == '__main__':
    tagFile = loadTagFile()
    errors = loopThrough(tagFile)
    printErrors(errors)
    # ic(errors)
    # getBackupFiles(errors)
    # fixErrors(errors)
