/* Copyright 2023 (c) Anna Schumaker */

PRAGMA user_version = 2;

/*
 * The `saved_track_data` table is missing the date added field, which
 * causes restored tracks to show up in the "New Tracks" playlist again.
 * We can fix this by storing the date that the track was initially added
 * to the database, and restoring it later.
 */

ALTER TABLE saved_track_data
	ADD COLUMN added DATE DEFAULT NULL;

UPDATE saved_track_data SET added = CURRENT_DATE;

DROP TRIGGER tracks_delete_save;
CREATE TRIGGER tracks_delete_save BEFORE DELETE ON tracks
	WHEN OLD.mbid != "" BEGIN
		INSERT INTO saved_track_data
			(mbid, favorite, playcount, lastplayed, laststarted, added)
		VALUES (OLD.mbid, OLD.favorite, OLD.playcount,
			OLD.lastplayed, OLD.laststarted, OLD.added);
	END;

DROP TRIGGER tracks_insert_restore;
CREATE TRIGGER tracks_insert_restore AFTER INSERT ON tracks
	WHEN NEW.mbid != "" BEGIN
		UPDATE tracks SET favorite = saved_track_data.favorite,
				  playcount = saved_track_data.playcount,
				  lastplayed = saved_track_data.lastplayed,
				  laststarted = saved_track_data.laststarted,
				  added = saved_track_data.added
			FROM saved_track_data
			WHERE tracks.mbid = saved_track_data.mbid AND
				tracks.mbid = NEW.mbid;
		DELETE FROM saved_track_data WHERE mbid = NEW.mbid;
	END;
