#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Marvin with a simple menu to start up with.
Marvin doesnt do anything, just presents a menu with some choices.
You should add functinoality to Marvin.
"""

import random
import re
import math

marvin_image = r"""
         _
        [ ]
       (   )
        |>|
     __/===\__
    //| o=o |\\
  <]  | o=o |  [>
      \=====/
     / / | \ \
    <_________>
"""

"""
Its an eternal loop, until q is pressed.
It should check the choice done by the user and call a appropriate
function.
"""

def run():
    """
    Program main function.
    Runs at end to load all functions.
    """

    while True:
        print(chr(27) + "[2J" + chr(27) + "[;H")
        print(marvin_image)
        print("Hi, I'm Marvin. I know it all. What can I do you for?")
        print("1) Present yourself to Marvin.")
        print("2) Celcius to Farenheit.")
        print("3) Wordmultiplier.")
        print("4) Sum and average.")
        print("5) Comparison.")
        print("6) Character addition.")
        print("7) Isogram.")
        print("8) Randomise string.")
        print("9) Anagram.")
        print("10) Akronym.")
        print("11) Mask.")
        print("A1) String check.")
        print("B1) Grade points.")
        print("B2) String compare.")
        print("q) Quit.")

        choice = input("--> ")

        if choice == "q":
            print("Bye, bye - and welcome back anytime!")
            break
        elif choice == "1":
            present()
        elif choice == "2":
            celcius_to_farenheit()
        elif choice == "3":
            wordmultiplier()
        elif choice == "4":
            sum_and_average()
        elif choice == "5":
            comparison()
        elif choice == "6":
            character_addition()
        elif choice == "7":
            isogram()
        elif choice == "8":
            chaosify()
        elif choice == "9":
            anagram()
        elif choice == "10":
            akronym()
        elif choice == "11":
            mask()
        elif choice == "A1":
            string_check()
        elif choice == "B1":
            grade_points()
        elif choice == "B2":
            string_compare()
        else:
            print("That is not a valid choice. You can only choose from the menu.")

        input("\nPress enter to continue...")

"""
Functions that are choices
"""

def present():
    """
    Presents marvin.
    """

    name = input("What is your name? ")
    print("\nMarvin says:\n")
    print("Hello %s, don't drink and code." % name)
    print("What can I do you for?!")

def celcius_to_farenheit():
    """
    Converts celcius to farenheit.
    """

    temp = input("Degrees celcius: ")

    print("\nMarvin says:\n")
    try:
        temp = int(temp)
        fahr = temp * 9 / 5 + 32
        print("The temperature in Fahrenheit is: %s." % str(fahr))
    except ValueError:
        print("The submitted value is not an integer.")

def wordmultiplier():
    """
    Prints a word multiple times.
    """

    word = input("Submit a word: ")
    mult = input("Multiplier: ")

    print("\nMarvin says:\n")
    try:
        mult = int(mult)

        i = 0
        while (i < mult):
            print(word)
            i += 1
    except ValueError:
        print("Submitted multiplier is not an integer.")

def sum_and_average():
    """
    Calculates the sum and average.
    """

    numbers = 0
    res = 0
    success = True
    
    while True:
        val = input("Next: ")

        if val == "done":
            break

        try:
            val = int(val)
            numbers += 1
            res += val
        except ValueError:
            print("\nMarvin says:\n")
            print("The submitted value is not an integer.")
            success = False
            break
    
    if success:
        avg = res / numbers
        print("\nMarvin says:\n")
        print("Sum: " + str(res) + " Avg: " + str(avg))

def comparison():
    """
    Compares some integers.
    """

    last = 0
        
    while True:
        val = input("Next: ")

        if val == "done":
            break

        try:
            val = int(val)

            res = ""
            if val < last:
                res = "smaller than"
            elif val == last:
                res = "equal to"
            elif val > last:
                res = "greater than"
            
            last = val

            print("\nMarvin says:\n")
            print("The number is %s the last number." % res)
        except ValueError:
            print("\nMarvin says:\n")
            print("The submitted value is not an integer.")
            break

def character_addition():
    """
    Multiplies all charachters seperated by -.
    """

    word = input("Enter a word: ")

    reps = 1
    res = ""

    for letter in word:
        if reps > 1:
            res += "-"

        res += repeat_char(letter, reps)

        reps += 1

    print("\nMarvin says:\n")
    print(res)

def isogram():
    """
    Finds out if a word is an isogram.
    """

    word = input("Enter a word: ")

    letters = ""
    res = "match"

    for letter in word:
        if letter in letters:
            res = "no match"
            break
        letters += letter
    
    print("\nMarvin says:\n")
    print(res)

def chaosify():
    """
    Brings chaos to the wor(l)d.
    """

    word = input("Submit a word: ")

    res = ""
    length = len(word)
    i = 0

    while i < length:
        r = random.randrange(len(word))
        res += word[r]
        word = word[:r] + word[(r + 1):]
        i += 1

    print("\nMarvin says:\n")
    print(res)

def anagram():
    """
    Finds out wheter two worsa ate anagarms.
    """

    first = input("Submit a word: ")
    second = input("Submit a word: ")

    first = first.lower()
    second = second.lower()

    second = second[::-1]

    print("\nMarvin says:\n")
    print("Matches: " + str(bool(first == second)))

def akronym():
    """
    Creates an akronym from a text.
    """

    value = input("Submit name: ")

    print("\nMarvin says:\n")
    print(re.sub('[^A-Z]', '', value))

def mask():
    """
    Mask all but the four last chars of a string.
    """

    word = input("Submit a word: ")

    print("\nMarvin says:\n")
    print(repeat_char("#", len(word) - 4) + word[-4:])

def string_check():
    """
    Checks a string for characters.
    """

    first = input("String to check: ")
    second = input("Look for: ")

    res = "match"

    for lookup in second:
        if lookup not in first:
            res = "no match"

    print("\nMarvin says:\n")
    print(res)

def grade_points():
    """
    Simple method to return grade from points calculation.
    """

    try:
        points_max = int(input("Maximum points: "))
        points = int(input("Your points: "))

        grade_scale = "FEDCBA"

        normalized = 0
        if points > 0:
            normalized = points / points_max

        grade_index = math.floor(normalized * 5.9) # Reduced by .1 to prevent index out of rage error.

        print("\nMarvin says:\n")
        print("Your grade is " + grade_scale[grade_index] + ".")
    except ValueError:
        print("\nMarvin says:\n")
        print("The submitted value is not an integer.")

def string_compare():
    """
    Checks if submitted string matches a set of rules.
    """

    word = input("Word: ")
    prefix = input("Prefix: ")
    suffix = input("Suffix: ")
    substr = input("Substring: ")

    startswith = word.startswith(prefix)
    endswith = word.endswith(suffix)
    contains = substr in word

    res = startswith and endswith and contains

    print("\nMarvin says:\n")
    print("Matches: " + str(res))   

"""
Functions used by choices.
"""

def repeat_char(char, times):
    """
    Repeats a character and returns the result.
    """

    i = 0
    res = ""

    while i < times:
        res += char
        i += 1

    return res

run()
