import os
import yaml


def conf_locate(cpath=None):
    """ Given a filesystem path, locate configuration files.
    If path is not defined, use current directory to start searching.
    Then go up one level each time, until a ".bucket3" dir is located.
    If located, will return (str) path to .bucket3.
    """
    if cpath and cpath != '.':
        # more testing need to be done here.
        return cpath
    confpath = None
    cwd = os.getcwd()
    h, t = os.path.split(cwd)  # head, tail

    while h != os.sep:
        if os.path.isdir(
                os.path.join(h, t, '.bucket3')
                ):
            confpath = os.path.join(h, t)
            break
        else:
            h, t = os.path.split(h)
    if not confpath:
        print 'bucket3.tools.conf_locate: Unable to locate a bucket3 configuration.'
        return None
    else:
        return confpath


def conf_get(cpath=None):
    """ Given a path (or cur dir if not), search for conf dir
    (going up if needed), then locate conf.yaml in conf dir,
    parse conf.yaml and return the configuration object.
    """
    cpath = conf_locate(cpath)
    if not cpath:
        print 'bucket3.tools.conf_get: Unable to read bucket3 configuration.'
        return None
    conf_file = os.path.join(cpath, '.bucket3', 'conf.yaml')
    conf = yaml.load(open(conf_file, mode='r').read())
    conf['root_dir'] = cpath
    conf['html_dir'] = os.path.join(cpath, 'html')
    conf['mentions_dir'] = os.path.join(cpath, 'mentions')

    return conf


def post_new(slug='', ext=None, cpath='.'):
    """ Create an empty post
    """
    import pkgutil
    from datetime import datetime

    s = pkgutil.get_data('bucket3', 'conf/post.example.md')
    s = s.replace('_date_time_now_', datetime.now().strftime('%Y-%m-%d %H:%M:%S %z'))
    s = s.replace('_post_slug_', slug)
    if not ext:
        c = conf_get(cpath)
        if not c:
            print "bucket3.b3tools.post_new: unable to locate conf.yaml."
            return 1
        if c['default_file_ext']:
            ext = c['default_file_ext']
        else:
            ext = ".md"

    prefix = datetime.now().strftime('%y%m%d')
    dirname = "%s-%s" % (prefix, slug)
    filename = os.path.join(dirname, "%s-%s.%s" % (prefix, slug, ext))
    os.mkdir(dirname)
    f = open(filename, 'w')
    f.write(s.encode('utf8'))
    f.close()
    print "Created %s." % filename


def blog_clean(cpath):
    """ Delete everyting generated by bucket3 (html, data files, etc.)
    """
    import shutil
    c = conf_get(cpath)
    if not c:
        print 'bucket3.b3tools.blog.clean: Unable to locate conf.yaml.'
        return 1

    html_dir = os.path.abspath(c['html_dir'])
    data_dir = os.path.abspath(os.path.join(c['root_dir'], '.bucket3', 'data'))
    fsdb_dir = os.path.abspath(os.path.join(c['root_dir'], '.bucket3', 'fsdb'))

    ok = raw_input('Delete EVERYTHING under \n%s and \n%s and \n%s \n(y/N)' % ( html_dir,data_dir, fsdb_dir ) )
    if ok in ('Y', 'y'):
        for p in [html_dir, data_dir, fsdb_dir]:
            for i in os.listdir(p):
                d = os.path.join(p, i)
                if os.path.isdir(d):
                    shutil.rmtree(path=d, ignore_errors=True)
                else:
                    os.remove(d)
            print "Deleted all files in %s." % p
    else:
        print "Canceled."


def blog_new(path):
    """ Create a blog skeleton. """
    import shutil
    import pkgutil

    path = os.path.abspath(path)  # "normalize" path.

    bucket3_dirs = (
        os.path.join(path, '.bucket3'),
        os.path.join(path, '.bucket3', 'themes'),
        os.path.join(path, 'posts'),
        os.path.join(path, 'html'),
        os.path.join(path, 'mentions'),
        os.path.join(path, 'log')
        )

    conf_file = os.path.join(path, '.bucket3', 'conf.yaml')

    print
    print "Checking file structure..."
    for d in bucket3_dirs:
        if not os.path.isdir(d):
            os.mkdir(d)
            print "   Created %s." % d
        else:
            print "   %s already exists." % d
    print 'Done.'

    if not os.path.isfile(conf_file):
        import pkgutil
        s = pkgutil.get_data('bucket3', 'conf/conf.example.yaml')
        s = s.replace('_top_blog_dir_', path)
        s = s.replace('_html_dir_', os.path.join(path, 'html'))
        f = open(conf_file, 'w')
        f.write(s.encode('utf8'))
        f.close()
        print "\nCreated: %s \nMake sure you edit it before moving on!\n" % conf_file
    else:
        print "%s already exists." % conf_file

    default_template_dir = os.path.join( os.path.dirname(
        os.path.abspath(__file__)),
        '_themes', 'bucket3')

    def_theme_path = os.path.join(path, '.bucket3', 'themes', 'bucket3')
    if not os.path.isdir(def_theme_path):
        shutil.copytree(default_template_dir, def_theme_path)
        print 'Copied default theme (bucket3).\n'
    else:
        print "%s already exists." % def_theme_path
