#!/usr/bin/env python

import os
import sys
from typing import List, Dict, Tuple


def print_color(text: str, color: str = "w") -> None:
    """
    Print colored text.

    :param text: text to print
    :param color: color of text
    :returns: None
    """
    code = {"r": 31, "g": 32, "y": 33, "b": 34, "m": 35, "c": 36, "w": 37}
    msg = f"\033[{code[color]}m{text}\033[0m"
    print(msg)


def find_patterns(files: List[str], pattern: str) -> Dict[str, Tuple[int, str]]:
    """
    Find lines containing given pattern in the files.

    :param files: names of files
    :param pattern: pattern to search
    :returns: dictionary with file names as keys and (line number, line) as
        values, where line number is counted from 1
    """
    patterns = dict()
    for f in files:
        patterns[f] = []
        try:
            with open(f, "r") as inf:
                content = inf.readlines()
                for nl, line in enumerate(content):
                    if line.find(pattern) != -1:
                        patterns[f].append((nl+1, line))
        except UnicodeDecodeError:
            print(f"ERROR opening {f}")
    return patterns


def print_patterns(patterns: Dict[str, Tuple[int, str]]) -> None:
    """
    Print output of find_patterns.

    :param patterns: output of find_patterns
    :returns: None
    """
    for key, value in patterns.items():
        if len(value) != 0:
            print_color(key, color="g")
            for line in value:
                print(line[0], line[1], end="")
            print()


def main():
    files = os.popen(f"find ./cmake ./sources ./tests -name {sys.argv[1]}").readlines()
    files = [_.rstrip("\n") for _ in files]
    patterns = find_patterns(files, sys.argv[2])
    print_patterns(patterns)


if __name__ == "__main__":
    main()
