#!python
# -*- coding: utf-8 -*-

import logging
import os
import platform
import subprocess
import click
from cleepcli.git import Git
from cleepcli.module import Module
from cleepcli.file import File
from cleepcli.watch import CleepWatchdog
import cleepcli.config as config

logging.basicConfig(level=logging.INFO, format=u'%(asctime)s %(levelname)s: %(message)s')

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

@core.command()
def coreget():
    """ 
    Get or update core content from official repository
    """
    g = Git()
    if not os.path.exists(config.CORE_SRC):
        g.clone_core()
    else:
        g.pull_core()

@core.command()
def coresync():
    """
    Synchronize core content between source and execution folders
    """
    f = File()
    f.core_sync()

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

@mod.command()
@click.option('--mod', required=True, help='Module name.')
def modsync(mod):
    """
    Synchronize core content between source and execution folders
    """
    f = File()
    f.module_sync(mod)

@mod.command()
@click.option('--name', prompt='Module name')
def modcreate(name):
    """
    Create new module skeleton
    """
    m = Module()
    m.create(name)

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

@watchdog.command()
@click.option('--quiet', is_flag=True, help='Disable logging.')
@click.option('--loglevel', default=logging.INFO, help='Logging level (10=DEBUG, 20=INFO, 30=WARN, 40=ERROR).')
def watch(quiet, loglevel):
    """
    Start watchdog that monitors filesystem changes on Cleep sources
    """
    if quiet:
        logging.disable(logging.CRITICAL)
    else:
        logging.getLogger().setLevel(loglevel)
        
    w = CleepWatchdog()
    w.watch()

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

@general.command()
def version():
    """
    Display cleep-cli version
    """
    click.echo(config.VERSION)


cli = click.CommandCollection(sources=[general, core, mod, watchdog])
if __name__ == '__main__':

    def is_raspbian():
        if platform.system()!='Linux':
            return False
        res = subprocess.Popen(u'cat /etc/os-release | grep -i raspbian | wc -l', stdout=subprocess.PIPE, shell=True)
        stdout = res.communicate()[0]
        if stdout.strip()=='0':
            return False
        return True

    #execute only on raspbian
    if is_raspbian():
        cli()
    else:
        click.echo('Cleep-cli runs only on raspbian distribution')

