#!/usr/bin/env python3

import argparse
import os
import time
from stmcli import bus, metro, data


def set_language(lang_file):
    lang = open(lang_file, "r")
    if "fr" in lang.read():
        return "Francais"
    else:
        return "Anglais"


def create_lang_file(lang_file):
    lang = open(lang_file, "a")
    lang.write("en")
    lang.close()


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-b", "--bus-number", help="# of the bus")
    parser.add_argument("-s", "--bus-stop-code", help="Code of the bus stop")
    parser.add_argument("-n", "--number-departure",
                        help="The number of departures to print. "
                             "Only works with both -b and -s specified")
    parser.add_argument("-d", "--date",
                        help="specify the date to use when getting"
                             " Departure times. Format: aaaammjj")
    parser.add_argument("-t", "--time",
                        help="specify the time to use when getting"
                        " Departure times. Format: HH:MM")
    parser.add_argument("-m", "--metro",
                        help="print the metro status for a given line"
                        " require an internet connection. Accepted options: "
                        "green, orange, yellow, blue, and all")
    parser.add_argument("-y", "--force-update", action='store_true',
                        help="Do not ask before updating")
    args = parser.parse_args()

    stmcli_data_dir = "{0}/.stmcli/".format(os.path.expanduser('~'))
    db_file = "{0}/stm.db".format(stmcli_data_dir)

    if not os.path.isdir(stmcli_data_dir):
        os.makedirs(stmcli_data_dir)

    lang_file = "{0}/{1}".format(stmcli_data_dir, "lang.txt")
    if not os.path.isfile(lang_file):
        create_lang_file(lang_file)

    # Checking for updates
    data.check_for_update(db_file, stmcli_data_dir, args.force_update)

    # Setting language
    lang = set_language(lang_file)

    # number of departures to print
    if not args.number_departure:
        number_departure = 10
    else:
        number_departure = int(args.number_departure)

    # Setting the time
    if not args.time:
        custom_time = time.strftime('%H:%M').split(':')
    else:
        custom_time = args.time.split(':')
        if len(custom_time) != 2:
            print("time format is HH:MM. Ex: 06:23")
            exit(1)
        elif len(str(custom_time[0])) != 2 or len(str(custom_time[1])) != 2:
            print("time format is HH:MM. Ex: 06:23")
            exit(1)

    # Setting the date
    if not args.date:
        date = time.strftime('%Y%m%d')
    else:
        if len(str(args.date)) != 8:
            print("date format is aaaammjj. Ex: 20160218")
            exit(1)
        else:
            if not data.date_in_scope(args.date, db_file):
                print("We don't have any info for this date.")
                exit(1)
            else:
                date = args.date

    # Print the next departures
    if args.bus_number and args.bus_stop_code:
        next_departures = bus.next_departures(args.bus_number,
                                              args.bus_stop_code,
                                              date,
                                              custom_time,
                                              number_departure,
                                              db_file)

        for i in next_departures:
            print(i)

    elif args.bus_number:
        # Print all bus stops for a bus
        bus_stops = bus.all_bus_stop(args.bus_number, db_file)

        for i in bus_stops:
            print(data.strip_accents(i))

    elif args.bus_stop_code:
        # Print all bus for a stop code
        bust = bus.all_bus_for_stop_code(args.bus_stop_code, db_file)

        for i in bust:
            print(i)

    # Print metro status
    if args.metro:
        accepted_input = ["green", "orange", "yellow", "blue", "verte",
                          "bleu", "jaune", "all"]

        if args.metro.lower() in accepted_input:
            metro.metro_status(args.metro, lang)
        else:
            print("Accepted inputs for the metro status are:")
            for i in accepted_input:
                print(i)
            exit(1)


if __name__ == '__main__':
    main()
