#!/usr/bin/env python
# coding=utf8
#
# 建立 CLI 命令列界面，整合指令的使用方式
#
# Author: Chun-Yu Lee (Mat) <matlinuxer2@gmail.com>
# License: MIT
#

from __future__ import print_function
import argparse
from h4_scripts import common
from h4_scripts.Config import Config
from h4_scripts.Wikidot import Wikidot
from h4_scripts.Gmail import Gmail
from h4_scripts.PTT import PTT
from h4_scripts.Logger import Logger
from h4_scripts.Facebook import Facebook, Graph
from h4_scripts.GoogleSpreadsheetAPI import Spreadsheet
from h4_scripts.AuthorData import AuthorData


def cmd_search(args):
    global config, logger, gmail, wikidot, root_url

    print("搜尋通訊錄", args.params)
    googledoc_user = config.Get('googledoc', 'email')
    googledoc_pass = config.Get('googledoc', 'password')
    spreadsheet = config.Get('googledoc', 'spreadsheet')
    worksheet = config.Get('googledoc', 'worksheet')

    spr = Spreadsheet(googledoc_user, googledoc_pass, spreadsheet)
    result = spr.getWorksheetCellArray(worksheet)
    for keyword in args.params:
            result = common.search_userdata(result, keyword)

    for k in result.keys():
            row = result[k]
            print("=" * 60)
            common.show_userdata(row)


def cmd_invite(args):
    global config, logger, gmail, wikidot, root_url

    # 這裡改從網頁上將通告內文抓下來，以後改用網頁來更新通告。
    Html = common.get_wikidot_content_body("http://www.hackingthursday.org/invite")
    Txt = common.html2txt(Html)
    this_thursday = common.getThursday(0)
    PartyDate = common.getThursday(0)
    subject = 'HackingThursday 固定聚會 (%s)' % this_thursday
    description = "地點：伯朗咖啡 (建國店)\n地址：台北市大安區建國南路一段 166 號\n(捷運忠孝新生站三號出口，沿忠孝東路走至建國南路右轉)\n\nWhat you can do in H4 :\n1. Code your code.\n2. Talk about OS, Programming, Hacking skills, Gossiping ...\n3. Meet new friends ~\n4. Hack and share anything !\n\nSee details :\nhttp://www.hackingthursday.org/\n\nWeekly Share :\nhttp://sync.in/h4"
    start_time = '%sT07:30:00-0400' % this_thursday
    end_time = '%sT10:00:00-0400' % this_thursday

    if args.use_fb:
        username = config.Get('facebook', 'username')
        password = config.Get('facebook', 'password')
        facebook_group_id = config.Get('facebook', 'group_id')

        def check_token():
            graph = Graph(config.Get('facebook', 'access_token'))

            if graph.getUID():
                logger.info('valid token')
                return config.Get('facebook', 'access_token')
            else:
                logger.info('invalid token, try get new one')
                fb = Facebook()
                if fb.login(username, password):
                    logger.info('login success')
                    token = fb.get_token()
                    if token:
                        logger.info('get new token')
                        config.Set('facebook', 'access_token', token)
                        return token
                    else:
                        logger.error('get token failed')
                else:
                    logger.info('login failed')

            return False

        token = check_token()
        if token:
            graph = Graph(token)

            if args.dryrun is not True:
                event_id = graph.createEvent(facebook_group_id, subject, description, start_time, end_time, dry_run=args.dryrun)
                if event_id:
                    logger.info('http://www.facebook.com/events/' + event_id)
                else:
                    logger.error('event create error')
            else:
                print("dryrun 模式，未貼文")

    if args.use_ptt:
        ID = config.Get('bbs', 'user')
        PASSWORD = config.Get('bbs', 'pass')
        board = 'Linux'

        ptt = PTT()

        if ptt.login(ID, PASSWORD):
            logger.info('login ptt')

        if ptt.enter(board):
            logger.info('enter %s board' % board)

        if args.dryrun is not True:
            if ptt.post(subject, TXT, dry_run=args.dryrun):
                logger.info('post article')
        else:
            print("dryrun 模式，未貼文")

        if ptt.quit():
            logger.info('quit ptt')

    if args.use_email:
        username = config.Get('gmail', 'username')
        password = config.Get('gmail', 'password')
        sender = config.Get('hackingthursday', 'who')  # 值日生的 email
        receiver = config.Get('hackingthursday', 'email_address')  # Google Groups 群組的 email

        gmail.login(username, password)
        if args.dryrun is not True:
            gmail.send(sender, receiver, subject, Txt, Html, dry_run=args.dryrun)
        else:
            print("dryrun 模式，未寄出")


def cmd_notify(args):
    global config, logger, gmail, wikidot, root_url

    if args.use_wiki:
        PartyDate = common.getThursday(0)

        username = config.Get('gmail', 'username')
        password = config.Get('gmail', 'password')
        sender = config.Get('hackingthursday', 'who')  # 值日生的 email
        receiver = config.Get('hackingthursday', 'email_address')  # Google Groups 群組的 email
        subject = "HackingThursday 聚會手記 (%s)" % PartyDate

        WikidotNoteURL = "http://www.hackingthursday.org/" + PartyDate
        MailContentHeader = common.mail_content_header
        MailContentFooter = common.mail_content_footer

        Html = """\
<html>
    <head>
        <title>HackingThursday</title>
    </head>
    <body>
    <pre>%s</pre>
    %s
    <pre>%s</pre>
    </body>
</html>
""" % (MailContentHeader, WikidotNoteURL, MailContentFooter)

        Txt = common.html2txt(Html.decode('utf-8'))

        gmail.login(username, password)
        if args.dryrun is not True:
            gmail.send(sender, receiver, subject, Txt, Html, dry_run=args.dryrun)
        else:
            print("dryrun 模式，未寄出")


def cmd_wikidot(args):
    global config, logger, gmail, wikidot, root_url

    if args.do_index:
        api_user = config.Get('wikidot', 'wikidot_api_user')
        api_key = config.Get('wikidot', 'wikidot_api_key')

        wikidot.auth(api_user, api_key)

        selecte_pages = []
        collection = []
        metadatas = []

        mask_pages = [
            'faq',
            'funding',
            'invite',
            'photoandvideo',
            'routine',
            'sandbox',
            'start',
        ]

        all_pages = wikidot.list_pages()
        for page in all_pages:
                prefix = ""
                if page.split(':').__len__() > 1:
                        prefix = page.split(':')[0]

                if page[0:2] == "20" and page[4] == "-" and page[7] == "-":
                        pass
                elif prefix != "":
                        pass
                else:
                        isInMask = False
                        if page in mask_pages:
                                isInMask = True
                        if not isInMask:
                                selecte_pages += [page]

        # 依更新日期作排序，最新的擺前面
        for i in range(0, selecte_pages.__len__(), 10):
                if i + 10 <= selecte_pages.__len__():
                        metadatas += wikidot.get_pages_meta(selecte_pages[i:i + 10]).items()
                else:
                        metadatas += wikidot.get_pages_meta(selecte_pages[i:selecte_pages.__len__()]).items()

        metadatas.sort(key=lambda x: x[1].get('updated_at'), reverse=True)
        selecte_pages = []
        print(metadatas)
        for item in metadatas:
                selecte_pages.append(item[0])

        # 開始產生選單
        page_of_index = ""
        for page in selecte_pages:
                print("處理頁面: ", page)
                metadata = wikidot.get_pages_meta([page])
                fullname = metadata.get(page).get('fullname').encode('utf8')
                title = metadata.get(page).get('title').encode('utf8')
                page_of_index += " * [[[%s|%s]]]\n" % (fullname, title)

        # 將新列表塞到主選單中
        nav_page = "nav:top"
        keyword_beg = "\n* [# Wiki]\n"
        keyword_end = "[!--Wiki--]"

        nav_top_page = wikidot.get_page(nav_page)
        nav_top_content = nav_top_page["content"].encode('utf8')

        new_nav_top_content = common.find_keyword_and_insert_content(nav_top_content, keyword_beg, keyword_end, page_of_index)

        print(new_nav_top_content)
        if args.dryrun is not True:
            wikidot.save_page(nav_page, content=new_nav_top_content)
        else:
            print("dryrun 模式，未寫入")

    if args.do_newpage:
        user_app = config.Get('wikidot', 'wikidot_api_user')
        key = config.Get('wikidot', 'wikidot_api_key')

        tomorrow = common.getThursday(0)
        lastweek = common.getThursday(-1)
        nextweek = common.getThursday(1)
        page = tomorrow
        title = tomorrow + ' 聚會手記'
        content = '''
        [[[ %s |上一週]]] || [[[ %s |下一週]]]

        [[toc]]

        [[html]]
        <iframe src='http://pad.hackingthursday.org?showControls=true&showChat=true&showLineNumbers=true&useMonospaceFont=false' width=675 height=400></iframe>
        [[/html]]
        ''' % (lastweek, nextweek)

        wikidot.auth(user_app, key)

        # 如果頁面不存在，則建立當週筆記頁
        if not wikidot.get_page(page):
            if args.dryrun is not True:
                if wikidot.save_page(page, title, content):
                    print(('To view : http://%s/%s' % (root_url, page)))
            else:
                print("dryrun 模式，未寫入")
        else:
            print("已經有筆記頁面了")

        # 更新上方選單項目
        top_bar_page = "nav:top"
        top_bar_title = 'Top Bar Menu'
        target_keyword = u"* [# 聚會手記]\n"
        note_page_link = u" * [[[" + tomorrow + "]]]\n"

        nav_top_page = wikidot.get_page(top_bar_page)
        nav_top_content = nav_top_page["content"]

        foundReturn = nav_top_content.find(tomorrow)
        if foundReturn < 0:
            new_nav_top_content = common.find_keyword_and_insert_content(nav_top_content, target_keyword, None, note_page_link)

            if args.dryrun is not True:
                if wikidot.save_page(top_bar_page, top_bar_title, new_nav_top_content):
                    print('To view : http://%s/%s' % (root_url, top_bar_page))
            else:
                print("dryrun 模式，未寫入")
        else:
            print("頁面已經有對應的選單項目了")

    if args.do_rebuild:
        print("更新 wiki 個人頁面")  # 用來取代 h4_wikidot_rebuild
        api_user = config.Get('wikidot', 'wikidot_api_user')
        api_key = config.Get('wikidot', 'wikidot_api_key')
        wikidot.auth(api_user, api_key)
        googledoc_user = config.Get('googledoc', 'email')
        googledoc_pass = config.Get('googledoc', 'password')
        spreadsheet = config.Get('googledoc', 'spreadsheet')
        worksheet = config.Get('googledoc', 'worksheet')
        dryrun = config.Get('googledoc', 'dryrun')

        spr = Spreadsheet(googledoc_user, googledoc_pass, spreadsheet)

        gmail.login(googledoc_user, googledoc_pass)

        ad_obj = AuthorData()

        user_mapping_pre = spr.getWorksheetCellArray(worksheet)
        ad_obj.user_mapping = common.convert_spreadsheet_to_userdata(user_mapping_pre)

        # 列出要處理的頁面
        user_pages = wikidot.list_user_pages()
        date_pages = wikidot.list_date_pages()
        wikidot.pull_and_cache_pages()  # 下載並更新頁面 cache

        date_pages.sort(reverse=True)  # 將最新日期放在最前面
        for page in date_pages:
            print("處理頁面: ", page)
            # workaround
            parts = wikidot.partition_page(page)
            ad_obj.parse_data_from_page(page, parts)

        #
        # 列出每個作者的統計資訊
        #
        print("==== 列出每個作者的統計資訊 ============================")
        authors = ad_obj.list_authors()
        for author in authors:
            cnt = 0
            for cc in ad_obj.collection:
                name = cc[0]
                if name == author:
                        cnt += 1
            ad_obj.authors_cnt += [(author, cnt)]

        ad_obj.authors_cnt.sort(key=lambda x: x[1], reverse=True)

        for row in ad_obj.authors_cnt:
            print("%s  %s" % (str(row[1]).rjust(4), row[0]))
        exit()
        #
        # 更新個別作者的頁面
        #
        print("==== 更新個別作者的頁面 =========================")
        authors = ad_obj.list_authors()
        for author in authors:
            page_of_author = ad_obj.process_page_per_author(author)
            page = "user:" + author.lower()
            user_head, page_of_author_orig = common.page_split_by_keyword(wikidot.get_page_content(page), "[[toc]]")
            cnt = ad_obj.get_author_cnt(author.lower())

            if page_of_author == page_of_author_orig or cnt <= 0:
                # 內容沒有變動，或無個人筆記的，跳過不更新
                continue

            # 顯示差異的部分
            out = common.get_diff_output_between_two_string(page_of_author_orig, page_of_author)
            print("==== %s 新舊差異的部分 ===========" % author)
            print(out)
            print("==================================")

            page_of_author = user_head + page_of_author  # 加上保留的使用者編輯內容

            author_data = ad_obj.find_author_by_name(author)
            name = author_data['rel_name']
            notify = author_data['notify']

            notify_enable = False
            if notify.lower().strip() in ["on", "v", "o", "yes", "y"]:
                notify_enable = True

            title = name + "的聚會手記"

            print("更新個人頁面: %s/%s" % (root_url, page))
            if dryrun is not True:
                if notify_enable is True:
                    wikidot.save_page(page, title, page_of_author)
                    collect_notify(author)
                else:
                    print("Notify 未開通: %s => %s/%s" % (author, root_url, page))
                    collect_unnotify(author)

        #
        # Calucate user statics
        #
        ary_local = ad_obj.list_authors()
        ary_remote = []
        for user_page in user_pages:
                user = user_page[5:]
                ary_remote += [user]

        ary_all = set(ary_local + ary_remote)

        ary_local_gt_remote = []
        ary_local_eq_remote = []
        ary_local_lt_remote = []

        for item in ary_all:
                if item in ary_local and item in ary_remote:
                        ary_local_eq_remote += [item]
                elif item in ary_local and not item in ary_remote:
                        ary_local_gt_remote += [item]
                elif not item in ary_local and item in ary_remote:
                        ary_local_lt_remote += [item]
                else:
                        print("例外: %s" % item)

        print("== 本地有，遠端有 ======================")
        for x in ary_local_eq_remote:
                print("%s/user:%s" % (root_url, x))
        print("== 本地有，遠端沒有 ====================")
        for x in ary_local_gt_remote:
                print("%s/user:%s" % (root_url, x))
        print("== 本地沒有，遠端有 ====================")
        for x in ary_local_lt_remote:
                print("%s/user:%s" % (root_url, x))
        print("========================================")

        # 展開作者列表
        page_of_index = ad_obj.make_index_of_authors()
        print(page_of_index)

        # 將作者列表塞到主選單中
        nav_page = "nav:top"
        keyword_beg = "\n* [# H4ckers]\n"
        keyword_end = "\n  * [[[user:non-en]]]\n"

        nav_top_page = wikidot.get_page(nav_page)
        nav_top_content = nav_top_page["content"].encode('utf8')

        new_nav_top_content = common.find_keyword_and_insert_content(nav_top_content, keyword_beg, keyword_end, page_of_index)
        if dryrun is not True:
            wikidot.save_page(nav_page, content=new_nav_top_content)

        #
        # 通知作者有頁面更新
        #
        print("==== 通知作者有頁面更新 ==================================")
        for author in ad_obj.collection3:
            author_data = ad_obj.find_author_by_name(author)
            rel_name = author_data['rel_name']
            url_name = author_data['url_name']
            email = author_data['email']
            notify = author_data['notify']
            notify_enable = False

            if notify.lower().strip() in ["on", "v", "o", "yes", "y"]:
                notify_enable = True

            if notify_enable:
                    print('To nofity: "%s" <%s> , %s/user:%s ' % (rel_name, email, root_url, url_name))
                    if dryrun is not True:
                        common.send_notify_mail(author, ad_obj, googledoc_user, root_url)
            else:
                    print('  skiping: "%s" <%s> , %s/user:%s ' % (rel_name, email, root_url, url_name))

        print("==== 未對應之作者 ==================================")
        for item in ad_obj.collection2:
                print("%s/%s '%s' " % (root_url, item[0], item[1]))

        print("==== 未開通之作者 ==================================")
        for item in ad_obj.collection4:
                print(item)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(dest='subcmd')

    # 通用選項
    parser.add_argument('-n', '--dry-run', help='跳過會寫入的動作', dest='dryrun', action='store_true')
    parser.add_argument('-v', '--verbose', help='顯示更詳細的訊息', dest='verbose', action='store_true')
    parser.add_argument('-d', '--debug', help='打開除錯訊息', dest='debug', action='store_true')

    # sub command for "search"
    parser_sub = subparsers.add_parser('search', help='搜尋線上通訊錄')
    parser_sub.add_argument('params', nargs='*', help='search keyword')
    parser_sub.set_defaults(func=cmd_search)

    # sub command for "notify"
    parser_sub = subparsers.add_parser('notify', help='內容更新通知')
    parser_sub.add_argument('--wiki', help='使用 wiki', dest='use_wiki', action='store_true')
    parser_sub.set_defaults(func=cmd_notify)

    # sub command for "invite"
    parser_sub = subparsers.add_parser('invite', help='發送聚會通告')
    parser_sub.add_argument('--fb', help='使用 facebook', dest='use_fb', action='store_true')
    parser_sub.add_argument('--ptt', help='使用 ptt', dest='use_ptt', action='store_true')
    parser_sub.add_argument('--email', help='使用 email', dest='use_email', action='store_true')
    parser_sub.set_defaults(func=cmd_invite)

    # sub command for "wikidot"
    parser_sub = subparsers.add_parser('wikidot', help='wikidot操作')
    parser_sub.add_argument('--do-index', help='更新編目', dest='do_index', action='store_true')
    parser_sub.add_argument('--do-newpage', help='新增當週頁面', dest='do_newpage', action='store_true')
    parser_sub.add_argument('--do-rebuild', help='更新作者頁面from聚會手記', dest='do_rebuild', action='store_true')
    parser_sub.set_defaults(func=cmd_wikidot)

    args = parser.parse_args()
    #print args; exit()
    if args.debug:
        print(args)

    if args.__contains__("func"):
        config = Config()
        logger = Logger('h4cli').__new__()
        gmail = Gmail()
        wikidot = Wikidot()
        wikidot.site = 'hackingthursday'
        root_url = 'http://www.hackingthursday.org'
        args.func(args)
    else:
        parser.print_help()
