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

"""
tarbell.configure
~~~~~~~~~~~~~~~~~

This module provides the Tarbell configure command.
"""

import os
import sys
import yaml
import shutil

from subprocess import call
from datetime import datetime
from clint.textui import colored, puts
from tarbell import LONG_VERSION

from .settings import Settings
from .oauth import get_drive_api_from_client_secrets
from .utils import show_error


def tarbell_configure(command, args):
    """
    Tarbell configuration routine.
    """
    puts("Configuring Tarbell. Press ctrl-c to bail out!")

    # Check if there's settings configured
    settings = Settings()
    path = settings.path

    prompt = True
    if len(args):
        prompt = False

    config = _get_or_create_config(path)

    if prompt or "drive" in args:
        config.update(_setup_google_spreadsheets(config, path, prompt))
    if prompt or "s3" in args:
        config.update(_setup_s3(config, path, prompt))
    if prompt or "path" in args:
        config.update(_setup_tarbell_project_path(config, path, prompt))
    if prompt or "templates" in args:
        if "project_templates" in config:
            override_templates = raw_input("\nFound Base Template config. Would you like to override them? [Default: No, 'none' to skip]")
            if override_templates and override_templates != "No" and  override_templates != "no" and override_templates != "N" and override_templates != "n":
                config.update(_setup_default_templates(config, path, prompt))
            else:
                puts("\nPreserving Base Template config...")
        else:
            config.update(_setup_default_templates(config, path, prompt))

    settings.config = config

    with open(path, 'w') as f:
        puts("\nWriting {0}".format(colored.green(path)))
        settings.save()

    if all:
        puts("\n- Done configuring Tarbell. Type `{0}` for help.\n"
             .format(colored.green("tarbell")))

    return settings


def _get_or_create_config(path, prompt=True):
    """
    Get or create a Tarbell configuration directory.
    """
    dirname = os.path.dirname(path)
    filename = os.path.basename(path)

    try:
        os.makedirs(dirname)
    except OSError:
        pass

    try:
        with open(path, 'r+') as f:
            if os.path.isfile(path):
                puts("{0} already exists, backing up".format(colored.green(path)))
                _backup(dirname, filename)
            return yaml.load(f)
    except IOError:
        return {}


def _setup_google_spreadsheets(settings, path, prompt=True):
    """
    Set up a Google spreadsheet.
    """
    ret = {}
    if prompt:
        use = raw_input("\nWould you like to use Google spreadsheets [Y/n]? ")
        if use.lower() != "y" and use != "":
            return settings

    dirname = os.path.dirname(path)
    path = os.path.join(dirname, "client_secrets.json")

    write_secrets = True
    if os.path.isfile(path):
        write_secrets_input = raw_input("client_secrets.json already exists. Would you like to overwrite it? [y/N] ")
        if not write_secrets_input.lower().startswith('y'):
            write_secrets = False

    if write_secrets:
        puts(("\nLogin in to Google and go to {0} to create an app and generate a "
              "\nclient_secrets authentication file. You should create credentials for an `installed app`. See "
              "\n{1} for more information."
              .format(colored.red("https://console.developers.google.com/project"),
                      colored.red("http://tarbell.readthedocs.org/en/{0}/install.html#configure-google-spreadsheet-access-optional".format(LONG_VERSION))
                     )
            ))

        secrets_path = raw_input(("\nWhere is your client secrets file? "
                                  "[~/Downloads/client_secrets.json] "
                                ))

        if secrets_path == "":
            secrets_path = os.path.join("~", "Downloads/client_secrets.json")

        secrets_path = os.path.expanduser(secrets_path)

        puts("\nCopying {0} to {1}\n"
             .format(colored.green(secrets_path),
                     colored.green(dirname))
        )

        _backup(dirname, "client_secrets.json")
        try:
            shutil.copy(secrets_path, os.path.join(dirname, 'client_secrets.json'))
        except shutil.Error, e: