#!/usr/bin/env python
import os
import time
import subprocess
import webbrowser

from backup_db import backup


# Set the Flask system variables
os.environ['FLASK_APP'] = 'monopyly'
os.environ['FLASK_ENV'] = 'development'

# Set the application specific system variables
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
BASE_DIR = os.path.dirname(SCRIPT_DIR)
INSTANCE_DIR = os.path.join(BASE_DIR, 'var/monopyly-instance')

# Initialize the database if it does not exist yet
if not os.path.isfile(os.path.join(INSTANCE_DIR, 'monopyly.sql')):
    os.system('flask init-db')

# Backup the database
backup()

# Run Flask
server = subprocess.Popen(['flask', 'run'])

# Run the default web browser
time.sleep(0.01)
webbrowser.open('http://127.0.0.1:5000/')

# Run the script until it's terminated
while True:
    try:
        time.sleep(1)
    except KeyboardInterrupt:
        print('\nClosing the Monopyly app...')
        break
