from core import cm, btoolsinit

btoolsinit.init()

from core import btoolsfile, fbauth, fbio

print "\nCOMMENT FETCHER\nExports all comments on selected posts into a CSV file\n"
fbauth.begin()

btoolsfile.import_ids_txt()
btoolsfile.smart_edit("%s/fb-comments.csv" % cm.export_dir)
btoolsfile.csv_write_line("Parent Post", "Parent ID", "Created", "Name", "User ID", "Comment", "Comment ID")

for post_id in btoolsfile.targetids:
    comment_count = 0
    comment_s = "s"
    post_content = fbio.fb_interact(fbio.get_content, post_id)
    comments_data = fbio.fb_interact(fbio.get_comments, post_id)
    for single_comment in comments_data:
        fromseek = cm.dict_to_datalist(single_comment.get("from"), "name", "id")
        rootseek_params = ["created_time", fromseek, "message", "id"]
        x_data = cm.dict_to_datalist(single_comment, *rootseek_params)
        btoolsfile.csv_write_line(post_content, post_id, *x_data)
        comment_count += 1
    fbio.remove_from_workingids(post_id)
    if comment_count is 0:
        btoolsfile.csv_write_line(post_content, post_id, "", "", "", "(no comments)")
    elif comment_count is 1:
        comment_s = ""
    print "Exported: %s (%s/%s, %s comment%s)" % (
        post_id,
from core import cm,btoolsinit
btoolsinit.init()

from core import btoolsfile,fbauth,fbio
import operator

print "\nINSIGHT FETCHER\nExports insight data on selected pages/posts into a CSV file\nMay work on pages that you do not administrate\n"
fbauth.begin()

btoolsfile.import_ids_txt()
btoolsfile.smart_edit("%s/fb-insights.csv"%cm.export_dir)

for obj_id in btoolsfile.targetids:
    obj_content=fbio.fb_interact(fbio.get_content,obj_id)
    btoolsfile.csv_write_line("%s (%s)"%(obj_content,obj_id))
    btoolsfile.csv_write_line()
    insights_data=fbio.fb_interact(fbio.get_insights,obj_id)
    for insight_data in insights_data:
        dtitle=insight_data["title"]
        ddesc=insight_data["description"]
        btoolsfile.csv_write_line("%s - %s"%(dtitle,ddesc))
        latest_data=insight_data["values"].pop().get("value")
        if type(latest_data) is dict:
            dkeys=[]
            dvalues=[]
            dsorted = sorted(latest_data.items(), key=operator.itemgetter(1), reverse=True)
            for k,v in dsorted:
                dkeys.append(k)
                dvalues.append(v)
            btoolsfile.csv_write_line(*dkeys)
            btoolsfile.csv_write_line(*dvalues)