module mymodule

import time
import os
import v.live
import math

const some_constant = f64(5.5)

fn append_to_file(fname string, s string) {
	mut f := os.open_append(fname) or {
		println('>>>> could not open file $fname for appending, err: $err ')
		return
	}
	f.writeln(s) or {
		println('>>>> could not write to $fname, err: $err ')
		return
	}
	// info := live.info()
	// f.writeln('>>> reloads: ${info.reloads} | ok reloads: ${info.reloads_ok}')
	f.close()
}

fn myprintln(s string) {
	append_to_file('#OUTPUT_FILE#', s)
	println(s)
	os.flush()
}

@[live]
fn pmessage() string {
	_ := mymodule.some_constant * math.sin(2.0 * math.pi * f64(time.ticks() % 6000) / 6000)
	return 'ORIGINAL'
}

const delay = 20

pub fn mymain() {
	mut info := live.info()
	info.recheck_period_ms = 5
	myprintln('START')
	myprintln('DATE: ' + time.now().str())
	pmessage()
	pmessage()
	max_cycles := os.getenv_opt('LIVE_CYCLES') or { '1' }.int()
	// NB: 1000 * 20 = maximum of ~20s runtime
	for i := 0; i < max_cycles; i++ {
		s := pmessage()
		myprintln(s)
		append_to_file(os.resource_abs_path(s + '.txt'), s)
		if s == 'STOP' {
			break
		}
		time.sleep(mymodule.delay * time.millisecond)
	}
	pmessage()
	pmessage()
	myprintln('DATE: ' + time.now().str())
	myprintln('END')
}
