#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
import re
import datetime
from shutil import copyfile

import commit_hook_common as commit_common
import hook_common


def reject_commit(original_path, question):
    reject_msg = (
        '\n[Incomplete Commit Message]\n'
        'Commit message is rejected because answer of "%s" is invalid.\n'
        'Please modify the commit message and retry.\n'
        'You can edit this failed commit using the following command:\n'
        '$ git commit -e -F $TB_HOME/.git/COMMIT_EDITMSG \n'
        % question.display_id
    )
    hook_common.print_colored_msg(hook_common.Color.RED, reject_msg)
    hook_common.print_colored_msg(hook_common.Color.YELLOW, question.error_msg)

    temp_file_name = original_path + "_" + \
        datetime.datetime.now().strftime("%Y%m%d%H%M%S") + ".tmp"
    copyfile(original_path, temp_file_name)
    print('\nYour edits have been saved to "%s" in .git directory.\n' % temp_file_name)
    print('Commit process is terminated with an error. Goodbye.\n')
    sys.exit(1)


def check_skip(input_msg):
    if input_msg.find('Merge branch') > -1 or \
            input_msg.find('Revert \"') > -1 or \
            input_msg.find('Content:') > -1 or \
            input_msg.find('Update submodules') > -1 or \
            input_msg.find('Merge remote-tracking branch') > -1:
        hook_common.print_colored_msg(hook_common.Color.GREEN, input_msg)
        return True
    return False

commit_msg_file_path = sys.argv[1]
commit_msg = ""

with open(commit_msg_file_path, 'r') as msg_file:
    content = ''
    input_msg = msg_file.read()

    if check_skip(input_msg):
        sys.exit(0)

    chunks = input_msg.split(".Q")[1:]
    assert len(chunks) == len(commit_common.QUESTIONS), \
        "Number of question and answer doesn't match."
    for chunk, question in zip(chunks, commit_common.QUESTIONS):
        chunk_answer = chunk.split('\n', 1)[1]
        chunk_answer = chunk_answer.rstrip()

        if len(chunk_answer) == 0:
            reject_commit(commit_msg_file_path, question)

        commit_msg += '%s%s' % (question.prefix, chunk_answer)
        commit_msg += '\n' * question.num_of_line_break


with open(commit_msg_file_path, 'w') as f:
    f.write("%s" % commit_msg)

hook_common.print_colored_msg(hook_common.Color.GREEN, 'Commit succeed!\n')
hook_common.print_colored_msg(hook_common.Color.GREEN, commit_msg)
