import os
import sys

from sbg_schema import Background

try:
    from sh import nitrogen
except ImportError:
    print("Error: you don't have nitrogen in your $PATH.")
    sys.exit(-1)

args = sys.argv[1:]

command = args[0]
args = args[1:]

def cycle():
    curbg = None
    try:
        curbg = Background.get(Background.current == True)
    except Background.DoesNotExist:
        curbg = Background.get(Background.id == 1)
    try:
        nextbg = Background.get(Background.id == curbg.id + 1)
    except Background.DoesNotExist:
        nextbg = Background.get(Background.id == 1)

    nitrogen("--save", "--set-zoom-fill", nextbg.path)
    curbg.current = False
    nextbg.current = True
    curbg.save()
    nextbg.save()

if command == "add":
    tag = args[0]
    fname = os.path.abspath(args[1])
    Background.insert(tag=tag, path=fname, current=False).execute()
if command == "rm":
    bg = Background.get(Background.id == int(args[0]))
    if bg.current:
        cycle()
    bg.delete_instance()
    bg.save()
if command == "set":
    oldbg = Background.get(Background.current == True)
    oldbg.current = False
    bg = Background.get(Background.id == int(args[0]))
    nitrogen("--save", "--set-zoom-fill", bg.path)
    bg.current = True
    bg.save()
    oldbg.save()
if command == "cycle":
    cycle()
if command == "list":
    for bg in Background.select():
        print("Background %d [%s]: %s (current: %r)" % (bg.id, bg.tag, bg.path, bg.current))

