#####################################################################
#                                                                   #
#  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 is responsible for fetching / connecting to the LBRY SDK
# it will take a more complex approach than simply talking to the SDK
# binary directly.

import os
import json
from subprocess import *
from urllib import request, parse

# EXAMPLE USAGE CODE

# Get:
# out = fetch.lbrynet("get",   {"uri":url} )
# Resolve:
# out = fetch.lbrynet("resolve",  {"urls":[url]}  )


def lbrynet(method="", params={}):

    # First we will make an attempt to use the request module
    try:

        # To test the SDK subprocess thing I have this little switch
        # 1/0 # Division by zero will trigger and error in this 'try'
        # and will skip it, to test the other method.
        
        data  = {"method":method,
                 "params":params}

        # The port of the LBRY SDK could be different for each user
        # so here I'm trying to solve this issue

        sdk_url = "http://localhost:5279"
        try:
            settings = open(os.path.expanduser('~/.local/share/lbry/lbrynet/daemon_settings.yml'))
            for line in settings:
                if line.startswith("api:"):
                    sdk_url = "http://"+line[5:]
        except:
            pass
        
        data = str(json.dumps(data))
        data = data.encode('utf-8')
        req = request.Request(sdk_url, data=data)
        resp = json.loads(request.urlopen(req).read())

        try:
            resp = resp["result"]
        except:
            pass
        
        return resp
        
    except:
        print("USING SDK VIA TERMINAL")
        # Attempt number 2: Fetch it regularly using the lbrynet via subprocess
        method = method.replace("_", " ")

        # TODO: make dynamic lbrynet executable
        sdk = "flbry/lbrynet"

        c = [sdk, method]

        # TODO: This is a mess. Things like 'resolve' or 'get' do not want to
        # act nicely. And there needs to be logic to translate them into a
        # proper ways. I added only 'resolve' and 'get' thus far. We need to
        # work with everything.
        
        for i in params:
            if type(params[i]) == list:
                for b in params[i]:
                    if method == "resolve" and i == "urls":
                        c.append(str(b))
                    else:
                        c.append("--"+i+"="+str(b))
            elif method == "get" and i == "uri":
                c.append(str(params[i]))
            else:
                c.append("--"+i+"="+str(params[i]))
        print(c)
        out = check_output(c)
        try:
            out = json.loads(out)
        except Exception as e:
            out = {}
        return out
        

