package main

type progress struct {
	Packs map[string]packProgress
}

func (p *progress) Pack(packID string) packProgress {
	if p.Packs == nil {
		p.Packs = map[string]packProgress{}
	}
	return p.Packs[packID]
}

func (p *progress) Level(packID, levelID string) levelProgress {
	pack := p.Pack(packID)
	return pack.Level(levelID)
}

func (p *progress) Update(packID, levelID string, update func(*levelProgress)) error {
	pack := p.Pack(packID)
	pack.Update(levelID, update)
	p.Packs[packID] = pack
	return p.store()
}

type packProgress struct {
	Levels map[string]levelProgress
}

func (p *packProgress) Level(id string) levelProgress {
	if p.Levels == nil {
		p.Levels = map[string]levelProgress{}
	}
	return p.Levels[id]
}

func (p *packProgress) Update(id string, update func(*levelProgress)) {
	level := p.Level(id)
	update(&level)
	p.Levels[id] = level
}

type levelProgress struct {
	Steps int
}

func (p *progress) store() error {
	path, err := userFile("progress.json")
	if err != nil {
		return err
	}
	return encodeJSON(path, p)
}

func (p *progress) load() error {
	path, err := userFile("progress.json")
	if err != nil {
		return err
	}
	var fromFile progress
	err = decodeJSON(path, &fromFile)
	if err != nil {
		return err
	}
	*p = fromFile
	return nil
}
