Anxiety, Depression and Addiction

Substance abuse can sometimes be an attempt to self-medicate an issue such as anxiety or depression. Often, they occur so closely together it is hard to distinguish which came first. Like the chicken or the egg, did the substance abuse cause anxiety or depression or did the depression and anxiety lead to substance abuse?