#!/usr/bin/env python3
###################################################################################################
# Spark Store Console. Originate from gfdgd-xi and leavelovetodepth

###################################################################################################
#################
# 引入所需的库
#################
import os
import sys
import json
import random
import shutil
import traceback
import subprocess
import webbrowser
import platform
#########################
# 程序信息
#########################


# 获取操作系统架构
machine_arch = platform.machine()

# 判断架构并设置store_url变量
if machine_arch == "aarch64":
    store_url = "aarch64-store"
elif machine_arch == "x86_64":
    store_url = "store"
elif machine_arch == "loong64":
    store_url = "loong64-store"
else:
    print("您当前的架构为{}，本版本商店暂不支持".format(machine_arch))
    input("按回车退出......")
    sys.exit(-1)



version = "4.3.3.1"
codeUrl = ["https://gitee.com/spark-store-project/spark-store/"]
uploadProgram = "https://upload.deepinos.org.cn/"
sparkStoreCodeUrl = "https://gitee.com/spark-store-project/spark-store/"
sparkStoreConsoleCodeUrl = "https://gitee.com/spark-store-project/spark-store/"
updateThings = '''4.3.3.1 版本同步'''
#########################
# 程序所需变量（可以修改）
#########################
#aptSource = "http://dcstore.spark-app.store"
aptSource = "https://mirrors.sdu.edu.cn/spark-store/"
programChineseName = ["社交沟通", "编程开发", "游戏娱乐", "图形图像", "音乐欣赏", "网络应用", "办公学习", "其他应用", "阅读翻译", "主题美化", "系统工具", "视频播放", "退出程序", "打开spk分享链接", "应用检查更新和应用投递~", "关于我们", "收藏"]
programSort = ["chat", "development", "games", "image_graphics", "music", "network", "office", "others", "reading", "themes", "tools", "video", "非分类项", "非分类项", "非分类项", "非分类项", "非分类项"]
debInstall = {1: "aptss"}
rootRun = {1: "sudo", 2: "pkexec"}
download = {1: "wget"}

###################
# 程序所需事件
###################
# 下载文件
def DownloadFile(URL, path):
    # 下载方案：
    # 1、wget
    # 提示：每种方案的语法不同，需要根据实际情况修改
    os.system('{} "{}" -q -P "{}"'.format(download[1], URL, path))  # 标准模式
    # os.system('{} "{}" -P "{}"'.format(download[1], URL, path))  # 调试模式

# 从源下载安装包
def InstallDeb(packageName):
    # root 的运行方案：
    # 1、使用 sudo（推荐）（默认）
    # 2、使用 pkexec（适用于在桌面环境使用）
    # deb 包安装方案：
    # 1、使用 aptss
    os.system("{} {} install {}={} -y".format(rootRun[1], debInstall[1], packageName,jsonThings['Version']))
    os.system("/opt/durapps/spark-store/bin/ss-feedback/sender-d {}/{}/".format(programSort[int(choose) - 1],jsonThings['Pkgname']))

# 从源重新下载安装包
def ReinstallDeb(packageName):
    # root 的运行方案：
    # 1、使用 sudo（推荐）（默认）
    # 2、使用 pkexec（适用于在桌面环境使用）
    # deb 包安装方案：
    # 1、使用 aptss
    os.system("{} {} install {} --reinstall".format(rootRun[1], debInstall[1], packageName))

# 从源重新下载安装包
def RemoveDeb(packageName):
    # root 的运行方案：
    # 1、使用 sudo（推荐）（默认）
    # 2、使用 pkexec（适用于在桌面环境使用）
    # deb 包安装方案：
    # 1、使用 aptss
    os.system("{} {} purge {}".format(rootRun[1], debInstall[1], packageName))

# 更新软件源
def UpdateAptPackage():
    # root 的运行方案：
    # 1、使用 sudo（推荐）（默认）
    # 2、使用 pkexec（适用于在桌面环境使用）
    # deb 包安装方案：
    # 1、使用 aptss
    os.system("{} {} update".format(rootRun[1], debInstall[1]))

# 更新操作系统
def UpgradeSystem():
    # root 的运行方案：
    # 1、使用 sudo（推荐）（默认）
    # 2、使用 pkexec（适用于在桌面环境使用）
    # deb 包安装方案：
    # 1、使用 aptss
    os.system("{} {} full-upgrade".format(rootRun[1], debInstall[1]))

# 清屏（终端/TTY）
def ClearConsole():
    # 调用系统命令
    os.system("clear")
    # Windows 则为：
    # os.system("cls")

# 打开默认程序
# 只支持 Linux，Windows 请忽略
def WatchPicture(path):
    subprocess.call(["xdg-open", path])



def Find(things, str):
    number = len(things)
    for i in range(0, number):
        if sys.argv[i] == str:
            # 如果值存在
            return i
            # 返回
    # 值不存在
    return -1
    # 返回

def ShowProgramInfomation(jsonThings):
    ClearConsole()
    os.system("echo Information!")
    print("标题：{}".format(jsonThings['Name']))
    print("版本：{}".format(jsonThings['Version']))
    print("包名：{}".format(jsonThings['Pkgname']))
    print("作者：{}".format(jsonThings['Author']))
    print("投稿者:{}".format(jsonThings['Contributor']))
    print("官网：{}".format(jsonThings['Website']))
    print("大小：{}".format(jsonThings['Size']))
    print("更新时间：{}".format(jsonThings['Update']))
    print("介绍：")
    print(jsonThings['More'].replace("\\n", "\n"))
    print()
    print("如果你要收藏，请输入“favourite”")
    print("如果想要安装/更新程序，请输入“install”")
    print("如果想要重新安装程序，请输入“reinstall”")
    print("如果想要卸载程序，请输入“remove”")
    print("如果想要使用默认的看图工具查看程序的有关截图，请输入“picture”")
    print("输入“spk”获取spk分享链接")
    print("如果你想退出本页，请输入“break”")
    print("如果你想回到首页，请输入“main”")
    print("如果你想要退出程序，请输入“exit”")
    while True:
        # 应用操作
        installChoose = input("选择==>").lower().strip()
        if installChoose == "install":
            InstallDeb(jsonThings['Pkgname'])
            input("按回车键继续……")
            break
        if installChoose == "reinstall":
            ReinstallDeb(jsonThings['Pkgname'])
            input("按回车键继续……")
            break
        if installChoose == "remove":
            RemoveDeb(jsonThings['Pkgname'])
            input("按回车键继续……")
            break
        if installChoose == "favourite":
            AddFavouriteList(jsonThings)
        if installChoose == "picture":
            if os.path.exists("/tmp/spark-store/picture"):
                shutil.rmtree("/tmp/spark-store/picture")
            os.mkdir("/tmp/spark-store/picture")
            for i in range(1, 5, 1):
                DownloadFile(
                    "{}/{}/{}/{}/screen_{}.png".format(aptSource,store_url, programSort[int(choose) - 1], jsonThings['Pkgname'],
                                                          str(i)),
                    "/tmp/spark-store/picture")
            WatchPicture("/tmp/spark-store/picture/screen_1.png")
        if installChoose == "main":
            return True
        if installChoose == "break":
            break
        if installChoose == "exit":
            quit()
        if installChoose == "spk":
            catagory = programSort[int(choose) - 1]
            packageName = jsonThings['Pkgname']
            print("spk://{}/{}/{}".format(store_url,catagory,packageName))
    return False

def OpenShareUrl(url):
    url = url.replace("spk://{}/".format(store_url), "")
    pie = url.index("/")
    packageName = url[pie + 1: len(url)]
    catagory = url[pie - 1: len(url)]
    if not os.path.exists("/tmp/spark-store/"):
        os.mkdir("/tmp/spark-store/")


    DownloadFile("{}/{}/{}/{}/app.json".format(aptSource, store_url,catagory, packageName),
                 "/tmp/spark-store/app.json")
    jsonFile = open("/tmp/spark-store/app.json")
    jsonThings = json.load(jsonFile)
    ShowProgramInfomation(jsonThings)
    #InstallDeb(packageName)

def ClasslySearchProgram(classly, things):
    global aptSource
    global stringtemp
    if os.path.exists("/tmp/spark-store/applist.json"):
        os.remove("/tmp/spark-store/applist.json")
    DownloadFile("{}/{}/{}/applist.json".format(aptSource, store_url, classly), "/tmp/spark-store")
    jsonFile = open("/tmp/spark-store/applist.json")
    jsonThings = json.load(jsonFile)
    rightThingsList = []
    rightThingsIndex = []
    for i in range(0, len(jsonThings) - 1):
        if things.lower() in jsonThings[i]['Name'].lower():
            rightThingsList.append(jsonThings[i]['Name'])
            rightThingsIndex.append(i + 1)
    return [rightThingsIndex, rightThingsList]

def AboutSparkStore():
    print("关于我们")
    print("Spark Store Console Version by shenmo. Origined from gfdgd-xi and leavelovedepth")
    print("QQ 群：872690351 865922727")

# 获取用户主目录
def get_home():
    return os.path.expanduser('~')

# 读取文本文档
def read_txt(path):
    f = open(path,"r") # 设置文件对象
    str = f.read() # 获取内容
    f.close() # 关闭文本对象
    return str # 返回结果

# 写入文本文档
def write_txt(path, things):
    file = open(path, 'w', encoding='UTF-8') # 设置文件对象
    file.write(things) # 写入文本
    file.close() # 关闭文本对象

def AddFavouriteList(things):
    global favouriteList
    favouriteList.append(things)
    write_txt("{}/.config/spark-store-console/favourite.json".format(homePath), json.dumps(favouriteList))

def DelFavouriteList(thingsIndex):
    global favouriteList
    del favouriteList[thingsIndex]
    write_txt("{}/.config/spark-store-console/favourite.json".format(homePath), json.dumps(favouriteList))

def CleanFavouriteList():
    global favouriteList
    favouriteList = []
    write_txt("{}/.config/spark-store-console/favourite.json".format(homePath), json.dumps(favouriteList))

###################
# 读取配置文件
###################
homePath = get_home()  # 获取用户“home”目录
if not os.path.exists("{}/.config/spark-store-console".format(homePath)):
    os.mkdir("{}/.config/spark-store-console".format(homePath))
if not os.path.exists("{}/.config/spark-store-console/favourite.json".format(homePath)):
    os.mknod("{}/.config/spark-store-console/favourite.json".format(homePath))
    write_txt("{}/.config/spark-store-console/favourite.json".format(homePath), json.dumps([]))
favouriteList = json.loads(read_txt("{}/.config/spark-store-console/favourite.json".format(homePath)))

###################
# 程序主事件
###################
if True:
    if Find(sys.argv, "--help") > 0:  # 读取参数
        print("星火应用商店（终端版）帮助：")
        print("--help\t显示帮助")
        print("--version\t显示版本")
        print("--about-us\t关于我们")
        print("--open-share-url \"星火应用商店分享链接\"\t打开星火应用商店分享链接")
        print("-q\t不显示分类并退出")
        print("--open-upload-program-site\t打开星火应用商店投稿页面")
        print("--open-spark-store-code-url\t打开星火应用商店代码托管平台")
        print("--open-spark-store-console-code-url\t打开星火应用商店终端版代码托管平台")
        quit()
    if Find(sys.argv, "--about-us") > 0:
        AboutSparkStore()
        quit()
    if Find(sys.argv, "--open-upload-program-site") > 0:
        webbrowser.open_new_tab(sparkStoreCodeUrl)
        quit()
    if Find(sys.argv, "--open-spark-store-console-code-url") > 0:
        webbrowser.open_new_tab(sparkStoreConsoleCodeUrl)
        quit()
    if Find(sys.argv, "--version") > 0:  # 读取参数
        print("版本：{}".format(version))
        print("源码：{}".format(codeUrl))
        quit()
    # 识别 Spark Store 分享链接，格式为： spk://store/分类/包名
    # 首先给 URL 删除协议
    # 然后获取“/”的位置
    # 然后分别截取前面（分类）和后面（软件包名）的字符串内容
    if Find(sys.argv, "--open-share-url") > 0:
        try:
            url = sys.argv[Find(sys.argv, "--open-share-url") + 1]
        except:
            traceback.print_exc()
            print("链接输入错误！")
        OpenShareUrl(url)
    if Find(sys.argv, "-q") > 0:  # 读取参数
        quit(0)
if not os.path.exists("/tmp/spark-store"):
    os.mkdir("/tmp/spark-store")
while True:
    # 选择分类
    ClearConsole()
    os.system("echo Welcome! Your arch is {}".format(machine_arch))
    print("本版本为终端版本，仅保留最基本功能以提升兼容性")
    print("终端版数据从镜像源获取，可能并非最新，敬请谅解！不影响应用更新，只影响应用展示")
    print("选择应用分类（输入“break”/“exit”退出程序）：")
    for i in range(1, len(programSort) + 1, 1):
        print("{}.{}".format(str(i), programChineseName[i - 1]))
    while True:
        choose = input(">").lower().strip()
        if choose == "13" or choose == "exit" or choose == "break":
            quit()
        if choose == "14":
            OpenShareUrl(input("输入星火应用商店分享链接：").lower().strip())
            input("按下回车键继续……")
            continue
        if choose == "15":
            print("1、投稿应用（推荐使用投稿器 spk://store/tools/spark-store-submitter）（若为arm架构投稿请加QQ群（详见星火官网下载页面 https://www.spark-app.store/download））")
            print("2、改进星火应用商店项目")
            print("3、改进星火应用商店控制台项目")
            print("4、更新 aptss 源")
            print("5、更新操作系统")
            print("6、检查商店内应用更新（使用zenity，需要GUI环境）")
            print("输入”break“返回首页，输入”exit“退出程序")
            while True:
                chooseDeveloper = input("更新程序==>").lower().strip()
                if chooseDeveloper == "1":
                    webbrowser.open_new_tab(uploadProgram)
                if chooseDeveloper == "2":
                    webbrowser.open_new_tab(sparkStoreCodeUrl)
                if chooseDeveloper == "3":
                    webbrowser.open_new_tab(sparkStoreConsoleCodeUrl)
                if chooseDeveloper == "4":
                    UpdateAptPackage()
                if chooseDeveloper == "5":
                    UpgradeSystem()
                if chooseDeveloper == "6":
                    os.system("/opt/durapps/spark-store/bin/update-upgrade/ss-do-upgrade.sh")

                if chooseDeveloper == "break":
                    break
                if chooseDeveloper == "exit":
                    quit()
            continue
        if choose == "16":
            AboutSparkStore()
            input("按下回车键继续……")
            continue
        if choose == "17":
            print("输入收藏项编号即可打开此收藏的详细信息")
            print("输入“show”显示收藏列表")
            print("输入“delete”删除某一项收藏")
            print("输入“clear”清空收藏")
            print("输入“break”返回主界面")
            print("输入“exit”退出程序")
            while True:
                favouriteChoose = input("收藏=>").lower().strip()
                if favouriteChoose == "show":
                    number = 0
                    for i in favouriteList:
                        number = number + 1
                        print("{}\t{}".format(str(number), i["Name"]))
                    continue
                if favouriteChoose == "delete":
                    delNumber = input("输入要删除数字的编号：")
                    try:
                        if not 1 <= int(delNumber) <= len(favouriteList):
                            print("输入错误！")
                            continue
                    except:
                        print("输入错误！")
                        continue
                    DelFavouriteList(int(delNumber) - 1)
                    continue
                if favouriteChoose == "clear":
                    if input("你确定吗？[Y/N]").upper().strip() == "Y":
                        CleanFavouriteList()
                        continue
                    print("用户取消")
                    continue
                if favouriteChoose == "break":
                    break
                if favouriteChoose == "exit":
                    quit()
                try:
                    if not 1 <= int(favouriteChoose) <= len(favouriteList):
                        print("输入错误！")
                        continue
                except:
                    print("输入错误！")
                    continue
                ShowProgramInfomation(favouriteList[int(favouriteChoose) - 1])
            continue
        try:
            if not 0 < int(choose) <= len(programSort) + 1:
                print("输入错误！")
                continue
        except:
            print("输入错误！")
            continue
        break
    #print(jsonThings[0]['Name'])
    while True:
        # 选择应用
        if os.path.exists("/tmp/spark-store/applist.json"):
            os.remove("/tmp/spark-store/applist.json")
        DownloadFile("{}/{}/{}/applist.json".format(aptSource,store_url, programSort[int(choose) - 1]), "/tmp/spark-store")
        jsonFile = open("/tmp/spark-store/applist.json")
        jsonThings = json.load(jsonFile)
        ClearConsole()

        
        for i in range(len(jsonThings)-1, -1, -1):
            print("{}.{}".format(str(i+1), jsonThings[i]['Name']))
        
        print("选择应用以便安装（输入“break”返回主页面，输入“exit”退出程序，输入“search”搜索）：")

        while True:
            chooseProgram = input(">").lower().strip()
            if chooseProgram == "search":
                while True:
                    searchThings = input("请输入搜索内容：").strip()
                    result = ClasslySearchProgram(programSort[int(choose) - 1], searchThings)
                    print("搜索结果：")
                    if len(result[0]) == 0:
                        print("没有对应项")
                    elif len(result[0]) == 1:
                        print("{}\t{}".format(result[0][0], result[1][0]))
                    else:
                        for i in range(len(result[0]) - 1, -1, -1):
                            print("{}\t{}".format(result[0][i], result[1][i]))
                    chooseProgram = input(">").lower().strip()
                    if not chooseProgram == "search":
                        break
            if chooseProgram == "break":
                break
            if chooseProgram == "exit":
                quit()
            try:
                if not 0 < int(chooseProgram) <= len(jsonThings):
                    print("输入错误！")
                    continue
            except:
                print("输入错误！")
                continue
            break


        if chooseProgram == "break":
            break
        if os.path.exists("/tmp/spark-store/app.json"):
            os.remove("/tmp/spark-store/app.json")
        DownloadFile("{}/{}/{}/{}/app.json".format(aptSource,store_url, programSort[int(choose) - 1], jsonThings[int(chooseProgram) - 1]['Pkgname']), "/tmp/spark-store")
        jsonFile = open("/tmp/spark-store/app.json")
        jsonThings = json.load(jsonFile)
        if ShowProgramInfomation(jsonThings):
            break
    
