import os
import time
import re


def utf8_length(text):
    if text is None:
        return 0
    len_text = len(text)
    len_text_utf8 = len(text.encode('utf-8'))
    # utf-8一个汉字占3个字符，减去原计数就是多出来的2/3，再除以2就是增量。再加回去即可
    size = int((len_text_utf8 - len_text) / 2 + len_text)
    return size


def tidy_done():

    with open('/opt/logs/TODO/done.txt', 'r') as donetxt, open('/tmp/tmp_done.txt', 'w') as tmpdone:
        lines = donetxt.readlines()
        for line in lines:
            tmpdone.write(line.strip() + '\n')

    os.system('mv /tmp/tmp_done.txt /opt/logs/TODO/done.txt')


def format_col_1(item):
    global number_of_days
    global item_no
    global auto_weekend

    end_time_date = item.strip()[-10:]
    try:
        end_time_stamp = time.strptime(end_time_date, "%Y-%m-%d")
    except Exception as Err:
        print('Error Encounted: ', end='')
        print(str(Err))
        print(f"Please modify /opt/logs/TODO/todo.txt @ line {item_no}  manually, and then run it again.\n")
        os._exit(1)

    end_time_stamp = time.mktime(end_time_stamp)
    now_time_stamp = int(time.time())
    number_of_days = round((end_time_stamp - now_time_stamp) / 3600 / 24 + 0.75, 2)
    # print('number_of_days-1:', number_of_days)

    if auto_weekend and number_of_days < 0:
        end_time_stamp += 604800
        end_time_date = time.strftime('%Y-%m-%d', time.localtime(end_time_stamp))
        item = item.strip()[:-10] + end_time_date
        number_of_days += 7

    item_format = re.sub(' +', ' ', item.strip())
    done.write(item_format)
    for i in range(16 - len(item_format)):
        done.write(' ')

    done.write('|')


def format_col_2(item):
    done.write(' ')
    done.write(item.strip())
    for i in range(12 - 1 - len(item.strip())):
        done.write(' ')

    done.write('|')


def format_col_3(item):
    global number_of_days
    # print('number_of_days-3:', number_of_days)
    item = 'T:' + str(number_of_days)

    done.write(' ')
    done.write(item.strip())
    for i in range(10 - 1 - len(item.strip())):
        done.write(' ')

    done.write('|')


def format_col_4(item):
    done.write(' ')
    try:
        with open('/tmp/col.log', 'r') as obj_col:
            width = int(obj_col.readline().strip())
    except:
        width = 125

    item_format = re.sub(' +', ' ', item.strip())
    len_of_task = utf8_length(item_format)
    # get the width of current terminal
    left_white = width - 11 - 12 - 10 - 5 - len_of_task - 8
    done.write(item_format + ' ' * left_white + '\n')


if __name__ == "__main__":

    number_of_days = 0
    item_no = 1
    # 0 signifies that task without priority, and 1 vice versa
    with open('/opt/logs/TODO/todo.txt', 'r') as todo, open('/tmp/tmp.txt', 'w') as done:
        for line in todo.readlines():
            col = 1
            auto_weekend = 0

            if line.strip() == '':
                continue
            elif 'Happy weekend~' in line:
                auto_weekend = 1
            else:
                pass

            for item in line.strip().split('|'):
                if col == 1:
                    format_col_1(item)
                elif col == 2:
                    format_col_2(item)
                elif col == 3:
                    format_col_3(item)
                elif col == 4:
                    format_col_4(item)
                else:
                    break

                col += 1
            item_no += 1


    os.system('mv /tmp/tmp.txt /opt/logs/TODO/todo.txt')
    tidy_done()






