import os
import sys
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 dir containing 
    bucket3.conf.yaml is located.
    If located, will return (str) the path.
    """
    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.isfile(
                os.path.join(h, t, 'bucket3.conf.yaml')
                ):
            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.')
        sys.exit(1)
    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 bucket3.conf.yaml in conf dir,
    parse bucket3.conf.yaml and return the configuration object.
    """
    cpath = conf_locate(cpath)
    if not cpath:
        print('bucket3.tools.conf_get: Unable to read bucket3 configuration.')
        sys.exit(1)
    conf_file = os.path.join(cpath, 'bucket3.conf.yaml')
    conf = yaml.full_load(open(conf_file, mode='r').read())
    conf['root_dir'] = cpath
    conf['html_dir'] = os.path.join(cpath, 'html')
    return conf


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

    c = conf_get(cpath)
    if not c:
        print("bucket3.b3tools.post_new: unable to locate bucket3.conf.yaml.")
        return 1
    try:
        local_template = os.path.join(c['root_dir'], 'templates', 'post.template.md')
        print("Trying template:", local_template)
        s =  open(local_template, 'r').read()
    except:
        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:
        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)
    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 bucket3.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 = 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]:
            if os.path.isdir(p):
                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, 'posts'),
        os.path.join(path, 'html'),
        os.path.join(path, 'log')
        )

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

    print("\n")
    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.\n')

    print("Generating config files...")
    if not os.path.isfile(conf_file):
        import pkgutil
        s = pkgutil.get_data('bucket3', 'conf/conf.example.yaml')
        f = open(conf_file, 'wb')
        f.write(s)
        f.close()
        print("   Created: %s \nMake sure you edit it before moving on!\n" % conf_file)
    else:
        print("   %s already exists." % conf_file)
    print("Done.\n")

    print("Installing default template files...")
    # cp bucket3/default/templates/ to blog_dir/templates/
    default_templates_dir = os.path.join( os.path.dirname(
        os.path.abspath(__file__)),
        'default', 'templates')
    inst_templates_dir = os.path.join(path, 'templates')
    if not os.path.isdir(inst_templates_dir):
        shutil.copytree(default_templates_dir, inst_templates_dir)
        print('   Copied default template files to %s.\n' % inst_templates_dir)
    else:
        print("   %s already exists." % inst_templates_dir)
    print("Done.\n")

    print("Installing default skeleton files...")
    # cp bucket3/default/skel/ to blog_dir/skel/
    default_skel_dir = os.path.join( os.path.dirname(
        os.path.abspath(__file__)),
        'default', 'skel')
    inst_skel_dir = os.path.join(path, 'skel')
    if not os.path.isdir(inst_skel_dir):
        shutil.copytree(default_skel_dir, inst_skel_dir)
        print('   Copied default skeleton files to %s.\n' % inst_skel_dir)
    else:
        print("   %s already exists." % inst_skel_dir)
    print("Done.\n")
