#####################################################################
#                                                                   #
#  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 fetch an LBRY URL directly and print out various
# options that the user may do with the publication.

from subprocess import *
import json
import os
from flbry.variables import *
from flbry import markdown

def get(url=""):
    
    # The user might type the word url and nothing else.
    
    if not url:
        url = input(" LBRY url :: ")
    else:
        print("    "+clr["bold"]+clr["bdma"]+"LBRY URL:",
              wdth(url, 78), clr["norm"])
    # Then let's fetch the url from our beloved SDK.

    out = check_output(["flbry/lbrynet",
                         "resolve", url])

    # Now we want to parse the json

    try:
        out = json.loads(out)
    except:
        print("   Connect to LBRY first.")
        return

    out = out[url]
    
    # Now let's print some useful information
    try:
        # This prints out the title
        print("    "+clr["bold"]+clr["bbma"]+"   TITLE:",
              clr["norm"]+clr["tbwh"]+clr["bbbu"]+wdth(out["value"]["title"], 78),
              clr["norm"])

        # This print out the channel name
        print("    "+clr["bold"]+clr["bdma"]+" CHANNEL:",
               clr["norm"]+clr["bold"]+clr["bdbu"]+wdth(out["signing_channel"]["name"], 38),
              clr["norm"]+clr["tbwh"]+clr["bdbu"]+wdth(out["signing_channel"]["value"]["title"], 39),
              clr["norm"]
              )
    except:
        pass
    try:
        # This will print the LBC amounts line
        fullamount = float(out["amount"]) + float(out["meta"]["support_amount"])
        print("    "+clr["bold"]+clr["bbma"]+"     LBC:",
              clr["norm"]+clr["tbwh"]+clr["bbbu"]+wdth(fullamount, 19),
              clr["bold"]+clr["bbma"]+"  UPLOAD:",
              clr["norm"]+clr["tbwh"]+clr["bbbu"]+wdth(out["amount"], 19),
              clr["bold"]+clr["bbma"]+" SUPPORT:",
              clr["norm"]+clr["tbwh"]+clr["bbbu"]+wdth(out["meta"]["support_amount"], 18),
              clr["norm"])
    except:
        pass
    try:

        # This line will print out the License.
        print("    "+clr["bold"]+clr["bdma"]+" LICENSE:",
              clr["norm"]+clr["bold"]+clr["bdbu"]+wdth(out["value"]["license"], 78),
              clr["norm"])

        # This line will print out file type and size of the file
        print("    "+clr["bold"]+clr["bbma"]+"    TYPE:",
              clr["norm"]+clr["tbwh"]+clr["bbbu"]+wdth(out["value"]["source"]["media_type"], 33),
              clr["bold"]+clr["bbma"]+"    SIZE:",
              clr["norm"]+clr["tbwh"]+clr["bbbu"]+wdth(csize(out["value"]["source"]["size"]), 34),
              clr["norm"])

        # This line will print out tags
        print("    "+clr["bold"]+clr["bdma"]+"    TAGS:",
              clr["norm"]+clr["bold"]+clr["bdbu"]+wdth(" "+tgz(out["value"]["tags"]), 78),
              clr["norm"])
    except:
        pass
    # Some things are too big to output like this in the terminal
    # so for them I want the user to type a command.

    print("    "+clr["bold"]+clr["bdma"],
          "                  --- for publication commands list type help --- ",
          wdth(" ", 20), clr["norm"])

    # So we are going to start a new while loop here. IK crazy.
    # this one will handle all the commands associated with the
    # currently selected publication.
    
    while True:
        c =  input(typing_dots())

        if not c:
            break

        elif c == "help":
            markdown.draw("help/url.md", "Publication Help")
            
        elif c == "https":
            Popen(['xdg-open',
                   url.replace("lbry://", "https://spee.ch/").replace("#", ":").replace("(", "%28").replace(")", "%29")], 
                              stdout=DEVNULL,
                              stderr=STDOUT)
        elif c == "odysee":
            Popen(['xdg-open',
                   url.replace("lbry://", "https://odysee.com/").replace("#", ":").replace("(", "%28").replace(")", "%29")], 
                              stdout=DEVNULL,
                              stderr=STDOUT)
        elif c.startswith("open"):

            # Selecting the software command in a smart way
            if len(c) < 6:
                p = input(" Open in : ")
            else:
                p = c[5:]

            Popen([p,
                   url.replace("lbry://", "https://spee.ch/").replace("#", ":").replace("(", "%28").replace(")", "%29")], 
                              stdout=DEVNULL,
                              stderr=STDOUT)
            
        elif c == "description":
            
            #print(out["value"]["description"])

            # Here I want to print out the description of the publication.
            # but since, they are most likely in the markdown format I
            # need to implement a simple markdown parser. Oh wait.... I
            # have one. For the article read function. How about using it
            # here?

            # First we need to save the description into a file. Let's use
            # /tmp/ since there files are automatically cleaned up by the
            # system.

            try:
                savedes = open("/tmp/fastlbrylastdescription.md", "w")
                savedes.write(out["value"]["description"])
                savedes.close()
            except:
                savedes = open("/tmp/fastlbrylastdescription.md", "w")
                savedes.write("This file has no description.")
                savedes.close()

            # Now let's just simply load the markdown on this file.
            markdown.draw("/tmp/fastlbrylastdescription.md", "Description")
            

        elif c == "play":

            # Then we want to tell the SDK to start downloading.
            playout = check_output(["flbry/lbrynet",
                                    "get", url])
            # Parsing the Json
            playout = json.loads(playout)
            
            # Then we want to launch the player
            Popen(["xdg-open",
                   playout['download_path']],
                              stdout=DEVNULL,
                              stderr=STDOUT)
        elif c == "save":

            # Then we want to tell the SDK to start downloading.
            playout = check_output(["flbry/lbrynet",
                                    "get", url])
            # Parsing the Json
            playout = json.loads(playout)
            
            print("    Saved to :", playout['download_path'])

        elif c == "read":
            # Then we want to tell the SDK to start downloading.
            playout = check_output(["flbry/lbrynet",
                                    "get", url])
            # Parsing the Json
            playout = json.loads(playout)

            # Present the article to the user.
            markdown.draw(playout['download_path'], out["value"]["title"])
