package applications

import (
	"git.openprivacy.ca/cwtch.im/tapir"
	"git.openprivacy.ca/cwtch.im/tapir/primitives/core"
	"git.openprivacy.ca/openprivacy/log"
)

// TranscriptApp defines a Tapir Meta-App which provides a global cryptographic transcript
type TranscriptApp struct {
	transcript *core.Transcript
}

// NewInstance creates a new TranscriptApp
func (TranscriptApp) NewInstance() tapir.Application {
	ta := new(TranscriptApp)
	return ta
}

// Init initializes the cryptographic transcript
func (ta *TranscriptApp) Init(connection tapir.Connection) {
	if ta.transcript != nil {
		ta.panic()
	}
	ta.transcript = core.NewTranscript("tapir-transcript")
}

// Transcript returns a pointer to the cryptographic transcript
func (ta *TranscriptApp) Transcript() *core.Transcript {
	return ta.transcript
}

// PropagateTranscript overrides the default transcript and propagates a transcript from a previous session
func (ta *TranscriptApp) PropagateTranscript(transcript *core.Transcript) {
	if ta.transcript != nil {
		ta.panic()
	}
	ta.transcript = transcript
}

func (ta *TranscriptApp) panic() {
	// Note: if this is ever happens it is a critical application bug
	// This will prevent a misuse of application chains that cause an earlier
	// transcript to be overwritten. Since we expect the security of many higher level applications
	// to be reliant on the randomness provided by the transcript we want to be actively hostile to any potential
	// misuse.
	log.Errorf("apps should not attempt to intitalize or overwrite a transcript once one has been initialized - this is a CRITICAL bug and so we have safely crashed")
	// We could silently fail to do anything here, but that is likely more dangerous in the long run...
	panic("apps should not attempt to intitalize  or overwrite a transcript a transcript once one has been initialized - this is a CRITICAL bug and so we have safely crashed")
}
