#####################################################################
#                                                                   #
#  THIS IS A SOURCE CODE FILE FROM A PROGRAM TO INTERACT WITH THE   #
# LBRY PROTOCOL ( lbry.com ). IT WILL USE THE LBRY SDK ( lbrynet )  #
# FROM THEIR REPOSITORY ( https://github.com/lbryio/lbry-sdk )      #
# WHICH I GONNA PRESENT TO YOU AS A BINARY. SINCE I DID NOT DEVELOP #
# IT AND I'M LAZY TO INTEGRATE IN A MORE SMART WAY. THE SOURCE CODE #
# OF THE SDK IS AVAILABLE IN THE REPOSITORY MENTIONED ABOVE.        #
#                                                                   #
#      ALL THE CODE IN THIS REPOSITORY INCLUDING THIS FILE IS       #
# (C) J.Y.Amihud and Other Contributors 2021. EXCEPT THE LBRY SDK.  #
# YOU CAN USE THIS FILE AND ANY OTHER FILE IN THIS REPOSITORY UNDER #
# THE TERMS OF GNU GENERAL PUBLIC LICENSE VERSION 3 OR ANY LATER    #
# VERSION. TO FIND THE FULL TEXT OF THE LICENSE GO TO THE GNU.ORG   #
# WEBSITE AT ( https://www.gnu.org/licenses/gpl-3.0.html ).         #
#                                                                   #
# THE LBRY SDK IS UNFORTUNATELY UNDER THE MIT LICENSE. IF YOU ARE   #
# NOT INTENDING TO USE MY CODE AND JUST THE SDK. YOU CAN FIND IT ON #
# THEIR OFFICIAL REPOSITORY ABOVE. THEIR LICENSE CHOICE DOES NOT    #
# SPREAD ONTO THIS PROJECT. DON'T GET A FALSE ASSUMPTION THAT SINCE #
# THEY USE A PUSH-OVER LICENSE, I GONNA DO THE SAME. I'M NOT.       #
#                                                                   #
# THE LICENSE CHOSEN FOR THIS PROJECT WILL PROTECT THE 4 ESSENTIAL  #
# FREEDOMS OF THE USER FURTHER, BY NOT ALLOWING ANY WHO TO CHANGE   #
# THE LICENSE AT WILL. SO NO PROPRIETARY SOFTWARE DEVELOPER COULD   #
# TAKE THIS CODE AND MAKE THEIR USER-SUBJUGATING SOFTWARE FROM IT.  #
#                                                                   #
#####################################################################

# This file will perform a simple search on the LBRY network.

from subprocess import *
import json

from flbry import url
from flbry.variables import *
from flbry import markdown
from flbry import channel

def list(claim_id, url, comment_id=""):


    # This function will list a list of comments of a certain claim_id
    # It will preview a very basic form of comment. You will have
    # to select a comment to interact with it further. Like read the
    # whole text, if it not short ( or in a markdown format ). Or
    # do other things like replies.

    w, h = tsize()
    
    page_size = h - 5
    page = 1
    
    while True:

        # Printing the search query and page number
        center("COMMENTS OF: "+url+" PAGE : "+str(page))

        if not comment_id:
            out = check_output(["flbry/lbrynet",
                         "comment", "list", claim_id,
                         '--page='+str(page),
                            '--page_size='+str(page_size)])
        else:
            out = check_output(["flbry/lbrynet",
                                "comment", "list", '--claim_id='+claim_id,
                            '--parent_id='+comment_id,
                         '--page='+str(page),
                            '--page_size='+str(page_size),
                            '--include_replies'])
            
        # Now we want to parse the json
        try:
            out = json.loads(out)
        except:
            print("   Connect to LBRY first.")
            return

        d = {"categories":["Tip LBC", "Comments", "Channel",  "Preview"],
                          "size":[1,1,2,5],
                          "data":[]}
        
        try:
            

            # List what we found
            for n, i in enumerate(out["items"]):
                
                
                preview = "---!Failed Loading comment---"
                support = 0
                replies = 0
                bywho = "@Anonymous"
                
                try:
                    comment = i["comment"]
                    preview = comment.replace("\n", " ")
                    support = i["support_amount"]
                    bywho = i["channel_name"]
                    replies = i["replies"]
                except:
                    pass
                
                d["data"].append([support, replies, bywho, preview])

            table(d)
                
            # Tell the user that he might want to load more
            center("---type 'more' to load more---")
            page = page +1

        # Error messages    
        except Exception as e:
            if "code" in out:
                print("    Error code: ", out["code"]  )
                if out["code"] == -32500:
                    print("   SDK is still starting. Patience!")
            else:
                print( e)
            return

        # Making sure that we stop every time a new page is reached
        c =  input(typing_dots())
        if c != "more":
            break
    try:
        c = int(c)
        
    except:
        return

    while True:
        view(out["items"][c])
        c = input(typing_dots())
        if not c:
            break
        try:
            c = int(c)
        except:
            return

def view(i):

    # This function will give a user an ability to interact / read a
    # given comment.

    
     preview = "---!Failed Loading comment---"
     comment = ""
     support = 0
     bywho = "@Anonymous"
     replies = 0

     try:
         comment = i["comment"]
         preview = comment.replace("\n", " ")
         support = i["support_amount"]
         bywho = i["channel_name"]
         replies = i["replies"]
     except:
         pass

     # TIP LBC     # COMMENTS ( REPLIES ) # CHANNEL 
     d = {"categories":["Tip LBC", "Comments",  "Channel"],
                          "size":[1,1,3],
                          "data":[[support, replies, bywho]]}
     table(d, False)

     # Preview
     d = {"categories":["Preview"],
                          "size":[1],
                          "data":[[preview]]}
     table(d, False)
     
     

     # The help thing
     center("--- for comment commands list type 'help' --- ")

     # let's implement commands
     while True:
        c =  input(typing_dots())

        if not c:
            break

        elif c == "help":
            markdown.draw("help/comments.md", "Comments Help")

        elif c == "read":
            
            savedes = open("/tmp/fastlbrylastcomment.md", "w")
            savedes.write(comment)
            savedes.close()
            
            markdown.draw("/tmp/fastlbrylastcomment.md", "Full Text Of a Comment")

        elif c == "channel":
            channel.simple(i["channel_url"])

        elif c == "comments":
            list(i["claim_id"], " ", i["comment_id"],)

        elif c.startswith("reply"):
            c = c + ' '
            post(i["claim_id"], c[c.find(" "):], i["comment_id"])
            

def post(claim_id, args,  parent_id=""):

    # This will post a comment under either a publication or a
    # comment as a reply. 

    # We gonna check if dunring typing reply the user added
    # anything after the word reply.

    #    reply emacs
    #    reply gedit
    #    reply vim

    # Or something like

    #    reply /home/username/filename.txt
    #    reply /home/username/filename.md

    # That might be useful to input multiline text.
    
    if len(args) > 1:
        a = args.split()[0]

        try:
            text = open(a, "r")
            text = text.read()
        except:
            text = open("/tmp/fastlbrycommentwriter.txt", "w")
            text.write("Type your reply here. Don't forget to save. Then return to FastLBRY.")
            text.close()

            import os
            os.system(a+" /tmp/fastlbrycommentwriter.txt")

            center("Press Enter when the file is ready and saved.")

            text = open("/tmp/fastlbrycommentwriter.txt", "r")
            text = text.read()
        
    else:
        text = input("   Text: ")
            
    
    post_as = channel.select("Reply as who? Select Channel.")
    

    if not post_as.startswith("@"):
        post_as = "@"+post_as
    

    if not parent_id:
        out = check_output(["flbry/lbrynet",
                         "comment", "create",
                        text,
                        '--channel_name='+post_as,
                        '--claim_id='+claim_id])
    else:
        out = check_output(["flbry/lbrynet",
                         "comment", "create",
                        text,
                        '--channel_name='+post_as,
                        '--parent_id='+parent_id,
                        '--claim_id='+claim_id])

    out = json.loads(out)
    if "message" in out:
        print("    "+clr["bbrd"]+clr["bold"]+wdth(out["message"], 89)+clr["norm"])
    else:
        print("    "+clr["bdgr"]+clr["bold"]+wdth("Comment is sent.", 89)+clr["norm"])
