#!/usr/bin/env python3
import glob
import logging
import os
import requests
import subprocess
import sys


from berry_video import list_files, auto_start, set_update, Player


logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())

ARGS_VIDEO = ["--no-osd", "-local"]
BASE_URL = "https://drive.google.com/u/0/uc?id={}&export=download"
BASE_PATH = "/var/tmp/berry/"

def get_video():
    files = list_files(BASE_PATH)
    return next(filter(lambda x: x["mimeType"] == "video/mp4", files), None)

def download_file(file):
        url_download = BASE_URL.format(file["id"])
        r = requests.get(url_download)
        file_path = os.path.join(BASE_PATH, file["name"])
        with open(file_path, 'wb') as fd:
            fd.write(r.content)

def update_video():
    local_videos = glob.glob(os.path.join(BASE_PATH, "*.mp4"))
    video = get_video()
    video_path = os.path.join(BASE_PATH, video["name"])
    if video_path not in local_videos:
        download_file(video)
        try:
            args = ARGS_VIDEO
            if "loop" in video_path:
                args.append("--loop")
            Player(video_path, args)#, "--loop"
        finally:
            if len(local_videos) > 0:
                command = ["rm"]
                command.extend(local_videos)
                subprocess.Popen(command)
        

def start():
    local_videos = glob.glob(os.path.join(BASE_PATH, "*.mp4"))
    if len(local_videos) > 0:
        video_path = os.path.join(BASE_PATH, local_videos[0])
        args = ARGS_VIDEO
        if "loop" in video_path:
            args.append("--loop")
        return Player(video_path, args), #"--loop"
    else:
        video = get_video()
        download_file(video)
        video_path = os.path.join(BASE_PATH, video["name"])
        args = ARGS_VIDEO
        if "loop" in video_path:
            args.append("--loop")
        return Player(video_path, args), #"--loop"

def is_int(value):
    try: 
        int(value)
        return True
    except ValueError:
        return False

if __name__ == "__main__":
    command = sys.argv[1]
    auto_start()
    import os
    if not os.path.exists(BASE_PATH):
        os.makedirs(BASE_PATH)
    if command == "storage" or command == "secret":
        id = sys.argv[2].replace("https://drive.google.com/file/d/","").replace("/view?usp=sharing","")
        data_file = { "id": id, "name": "{}.json".format(command) } 
        download_file(data_file)
    else:
        minute = sys.argv[2] if len(sys.argv) > 2 else 5
        set_update(minute)
        if command == "start":
            start()
        elif command == "update":
            update_video()


