#!/usr/bin/env python3
import itertools
import json
import os
from pprint import pprint

import click
import requests
from git import Repo

from gitlike.config import write_config, get_config_path, config_is_valid
from gitlike.git_wrapper import git_blame
from gitlike.gitlike_service import handle_service
from gitlike.like import like_file
from gitlike.shared import get_api_key, get_current_git_user, get_likes


@click.group()
def main():
    pass



@main.command()
@click.argument('file', type=click.Path(exists=True))
@click.argument('from_line')
@click.argument('to_line')
def like(file, from_line, to_line):
    if not config_is_valid():
        exit_with_invalid_config()

    like_file(file, from_line, to_line)


@main.command()
@click.argument('email')
@click.option('--code', help='The access code you received via email.')
def claim(email, code):
    if code is not None:
        # validate access code
        validationRes = requests.post('https://1nvgpilww4.execute-api.eu-central-1.amazonaws.com/dev/access/validate',
                      json.dumps({'user': email, 'code': code}),
                      headers={'X-API-KEY': get_api_key()})
        # print(validationRes.text)
        isValid = validationRes.json()['isValid']

        if isValid:
            write_config({'code': code, 'email': email})
            click.echo(
                f'''
You successfully claimed {email}. 
Once you started the git-like dameon process you will start receiving likes!

Liking a file:
$ git-like like FILE LINE_FROM LINE_TO

Starting the git-like daemon:
\u001b[32m$ git-like start \u001b[37m

Stopping the git-like daemon:
\u001b[31m$ git-like stop \u001b[37m
''')
        else:
            click.echo('The provided access code was invalid.')
            exit(1)
    else:
        # create access code
        requests.post('https://1nvgpilww4.execute-api.eu-central-1.amazonaws.com/dev/access',
                      json.dumps({'email': email}),
                      headers={'X-API-KEY': get_api_key()})
        click.echo(f'''We send you a confirmation mail. Claim your email by using: 
git-like claim {email} --code [CODE].
''')


@main.command()
def start():
    if not config_is_valid():
        exit_with_invalid_config()
    handle_service('start')


@main.command()
def stop():
    if not config_is_valid():
        exit_with_invalid_config()
    handle_service('stop')

@main.command()
def ls():
    likes = get_likes()
    project_grouped = {k: list(v) for k,v in itertools.groupby(likes, lambda like: like['project'])}

    for p, likes_p in project_grouped.items():
        click.echo(p)

        file_grouped = {k: list(v) for k, v in itertools.groupby(likes, lambda like: like['file'])}
        for file_name, likes_f in file_grouped.items():
            click.echo(f'   {file_name}')
            for like_f in list(likes_f):
                click.echo(f"       {like_f['from_l']}-{like_f['to_l']}")

def exit_with_invalid_config():
    click.echo(
        'Your .gitlike config is invalid. Please check it before continuing. You can find the config under' + get_config_path())
    exit(1)


def remove_duplicates(l):
    return list(dict.fromkeys(l))


if __name__ == '__main__':
    main()
