#starter program 2 - week 8

import csv

def addContact():
    contact=[]
    contact.append(input("Enter their name: "))
    contact.append(input("Enter their address: "))
    contact.append(input("Enter their Telephone Number: "))
    contact.append(input("Enter their E-Mail Address: "))
    with open('addressBook.txt', 'a', newline='') as f:
        file = csv.writer(f, delimiter=',')
        file.writerow(contact)
    print("Contact added")

def showContact():
    name=input("Enter the name: ")
    with open('addressBook.txt', 'r') as f:
        reader = csv.reader(f)
        contacts = list(reader)
    for contact in contacts:
        if contact[0] == name:
            for detail in contact:
                print(detail)

def showAllContacts():
    with open('addressBook.txt', 'r') as f:
        reader = csv.reader(f)
        contacts = list(reader)
    for contact in contacts:
        for detail in contact:
            print(detail+"\t", end="")
        print("\n")

def editContact():
    with open('addressBook.txt', 'r') as f:
        reader = csv.reader(f)
        contacts = list(reader)
    
    invalid=True
    while invalid:
        name=input("Enter the name of the contact you want to update: ")
        for i in range(len(contacts)):
            if contacts[i][0] == name:
                index=i
                invalid=False
        if invalid:
            print("Name not found, please try again")
            
    print("Enter their updated details")
    contacts[index][0]=input("Enter their name: ")
    contacts[index][1]=input("Enter their address: ")
    contacts[index][2]=input("Enter their Telephone Number: ")
    contacts[index][3]=input("Enter their E-Mail Address: ")

    with open('addressBook.txt', 'w', newline='') as f:
        file = csv.writer(f, delimiter=',')
        file.writerows(contacts)
    print("Contact updated")

repeat=True
while repeat==True:
    choice=input("1. Add Contact\n2. Find Contact\n3. Show All Contacts\n4. Edit Contact\n")
    if choice=="1":
        addContact()
    elif choice=="2":
        showContact()
    elif choice=="3":
        showAllContacts()
    elif choice=="4":
        editContact()






