from sys import stdin
import tokenize


__version__ = '0.0.2'


class DoubleQuoteChecker(object):
    name = __name__
    version = __version__

    def __init__(self, tree, filename='(none)', builtins=None):
        self.file = (filename == 'stdin' and stdin) or filename

    def run(self):
        if self.file == stdin:
            file_contents = self.file
        else:
            with open(self.file, 'r') as file_to_check:
                file_contents = file_to_check.readlines()

        noqa_line_numbers = get_noqa_lines(file_contents)
        errors = get_double_quotes_errors(file_contents)

        for error in errors:
            if error.get('line') not in noqa_line_numbers:
                yield (error.get('line'), error.get('col'), error.get('message'), type(self))


def get_noqa_lines(file_contents):
    tokens = tokenize.generate_tokens(lambda L=iter(file_contents): next(L))
    return [token.start[0]
            for token in tokens
            if token.type == tokenize.COMMENT and token.string.endswith('noqa')]


def get_double_quotes_errors(file_contents):
    tokens = tokenize.generate_tokens(lambda L=iter(file_contents): next(L))
    for token in tokens:
        if token.type != tokenize.STRING:
            # ignore non strings
            continue

        if not token.string.startswith('"'):
            # ignore strings that do not start with doubles
            continue

        if token.string.startswith('"""'):
            # ignore multiline strings
            continue

        if "'" in token.string:
            # ignore singles wrapped in doubles
            continue

        start_row, start_col = token.start
        yield {
            'message': 'Q000 Remove Double quotes.',
            'line': start_row,
            'col': start_col
        }

@@ -913,22 +913,19 @@
 n %5Btoken
-.start
+%5B2%5D
 %5B0%5D%0A    
@@ -972,21 +972,19 @@
 if token
-.type
+%5B0%5D
  == toke
@@ -1005,23 +1005,19 @@
 nd token
-.string
+%5B1%5D
 .endswit
@@ -1196,13 +1196,11 @@
 oken
-.type
+%5B0%5D
  != 
@@ -1287,31 +1287,27 @@
 if not token
-.string
+%5B1%5D
 .startswith(
@@ -1410,23 +1410,19 @@
 if token
-.string
+%5B1%5D
 .startsw
@@ -1521,15 +1521,11 @@
 oken
-.string
+%5B1%5D
 :%0A  
@@ -1628,22 +1628,19 @@
  = token
-.start
+%5B2%5D
 %0A       

Support Python 2 style tokenizer