"""
SDD12 - File Handling: Writing
Live-coding demo for the instruction phase.

How to use:
  - Build each TODO section live, following the lesson's worked examples
    in the same order. Examples 2 and 3 are deliberate mistakes - let
    them show their (wrong or crashing) output on screen.
  - The finished version is in SDD12_File_Handling_Write_answers.py.

Run with: python3 SDD12_File_Handling_Write_demo.py
"""

from dataclasses import dataclass


@dataclass
class Item:
    name: str
    price: int
    stock: int


itemRecords = [
    Item("Crisps", 60, 24),
    Item("Juice", 90, 15),
    Item("Chocolate", 75, 30),
    Item("Water", 50, 40)
]


# ----- Example 1: writing a single line of plain text -----
# TODO: open "notice.txt" in "w" mode, write "Tuck shop closes early on
# Fridays", close the file. Then open it again in "a" mode and write
# "Muffin,120,18\n" to tuckshop.csv to show appending vs overwriting.


# ----- Example 2: forgetting newline characters between writes -----
# TODO: open "test.txt" in "w" mode, write("line one") then
# write("line two") with NO \n, close, then read it back to show the
# two lines have run together into "line oneline two".


# ----- Example 3: TypeError from an unconverted field -----
newItem = Item("Muffin", 120, 18)
# TODO: try building
#   line = newItem.name + "," + newItem.price + "," + newItem.stock
# and let it crash with a TypeError, because .price and .stock are
# ints, not strings, and + can't mix the two. Fix it live by wrapping
# them in str().


# ----- Example 4: writing a whole array of records to CSV -----
itemRecords.append(newItem)
# TODO: open "tuckshop.csv" in "w" mode. Loop through itemRecords,
# building each line as
#   item.name + "," + str(item.price) + "," + str(item.stock) + "\n"
# and write() it. Close the file, then read tuckshop.csv back to check.
