# -*- coding: utf-8 -*-

"""
    this is the moduler to count code lines in the given directory.
    It ignore blank line but counts the note line.such as #...,//...
    __author__ = 'R'
    time: 2017.4.21
"""

import sys, os

filetype = ['.c', '.cpp', '.java', '.py', '.h']
linescount = 0
filescount = 0
c_count = 0
cpp_count = 0
java_count = 0
py_count = 0
h_count = 0

defaultPath = r'D:\GitHub\GeometryEncoding'


def countLines(filepath):
    global c_count, cpp_count, java_count, py_count, h_count
    lines = 0
    # 这里打开文件经常有无法编码或者无法解码的问题；
    with open(filepath, 'rb') as f:
        temp = os.path.split(filepath)[1]
        for line in f:
            if line.strip() != '':
                if temp.endswith(filetype[0]):
                    c_count += 1
                    lines += 1
                elif temp.endswith(filetype[1]):
                    cpp_count += 1
                    lines += 1
                elif temp.endswith(filetype[2]):
                    java_count += 1
                    lines += 1
                elif temp.endswith(filetype[3]):
                    py_count += 1
                    lines += 1
                elif temp.endswith(filetype[4]):
                    h_count += 1
                    lines += 1
                # 这样会导致将所有文件的行数都统计进去了，比如.txt，二进制；
                # lines += 1
                # print(line)
    return lines


def countFilesLines(path):
    lines = 0
    global linescount, filescount
    for rootpath, subdirs, filenames in os.walk(path):
        for f in filenames:
            lines += countLines(os.path.join(rootpath, f))
            filescount += 1
    linescount = lines
    return


if __name__ == '__main__':
    print('counting...')
    if len(sys.argv) >= 2:
        countFilesLines(sys.argv[1])
    else:
        countFilesLines(defaultPath)
    print("total files: ", str(filescount))
    print('total code lines: ' + str(linescount))
    print('total c conde lines: ' + str(c_count))
    print('total cpp code lines: ' + str(cpp_count))
    print('total java code lines: ' + str(java_count))
    print('total python code lines: ' + str(py_count))
    print('total .h code lines: ' + str(h_count))
