#!/usr/bin/python

import argparse
import shutil
import sqlite3
import tempfile
import os

def main():
    parser = argparse.ArgumentParser(description='Command line arguments')
    parser.add_argument('-d', '--db', required=True, help='database location')
    parser.add_argument('-t', '--tag', type=int, required=False, help='tag id')
    parser.add_argument('-n', '--number', type=int, default=4, help='number')
    args = parser.parse_args()

    # Copy db to temp location
    temp_dir = tempfile.gettempdir()
    temp_db = os.path.join(temp_dir, 'pmvg.db')
    if not os.path.exists(temp_db):
        shutil.copy2(args.db, temp_db)

    # Open temp db with sqlite
    conn = sqlite3.connect(temp_db)
    cursor = conn.cursor()

    # Print names of all tables
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
    tables = cursor.fetchall()
    print("Tables:")
    for table in tables:
        print(table[0])
    print()

    # Print schema of scenes_tags table
    cursor.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name='scenes_tags'")
    schema = cursor.fetchone()
    print("Schema for scenes_tags:")
    print(schema[0])
    print()

    # Print data of tags table if tag id not provided
    if not args.tag:
        cursor.execute("SELECT * FROM tags")
        tags = cursor.fetchall()
        print("Table: tags")
        for tag in tags:
            print(tag)
        print("Select a tag with -t")
        exit()

    # Get random scenes based on tag id
    cursor.execute(f"SELECT * FROM scenes_tags WHERE tag_id = {args.tag} ORDER BY RANDOM() LIMIT {args.number}")
    scenes = cursor.fetchall()
    print(f"\nRandom {args.number} scenes with tag_id {args.tag}:")
    for scene in scenes:
        scene_id = scene[0]
        url = f"http://localhost:9999/scene/{scene_id}/stream"
        os.system(f"nohup mpv --volume=0 {url} </dev/null >/dev/null 2>&1 &")
        print(scene)
    os._exit(0)

if __name__ == '__main__':
    main()
