let theShader;
let img;
 
let shaderTexture;

var yokeX = 0.5;
var yokeY = 0.5;

var time = 0.0;
var currShader;
var mySound;
let myFont;

var mic;

let startedPlaying = false;

function preload(){
  theShader = loadShader('assets/pt2.vert', 'assets/pt2.frag');
  soundFormats('mp3', 'ogg');
  mySound = loadSound('assets/rp-ngc4889.mp3');
  img = loadImage('assets/shadertoy-rustymetal.png');
  myFont = loadFont('assets/glacial-indifference.bold.otf');
}

let numberOfPresses = 0;
function mouseDragged() {
  if (numberOfPresses > 0) {
    
    yokeX = mouseX/width;
    yokeY = 1.0-mouseY/height;
  }
}
function mousePressed() {
  numberOfPresses ++ ;
  if (mouseX > 0 && mouseX < displayWidth && mouseY > 0 && mouseY < displayHeight) {
    let fs = !fullscreen();
    fullscreen(fs);
    if (fs) {
          mySound.play();
		  startedPlaying = true;
		  noCursor();
    }
    else {
      mySound.stop();
      startedPlaying = false;
	  cursor();
    }
    numberOfPresses = 0;
    time =  -1.954*1.0;
;
  }
}
function keyPressed() 
{
  if (key == 'f') {    
    let fs = !fullscreen();
    fullscreen(fs);
    if (!fs) {
      mySound.stop();
    }
  }
	if (keyCode === ESCAPE) {
		mySound.stop();
	}
  if (!fullScreen() && mySound.isPlaying())
	 mySound.stop();
}

function setup() {
  // shaders require WEBGL mode to work
  createCanvas(displayWidth, displayHeight, WEBGL);
  //createCanvas(1280, 720, WEBGL);
  pixelDensity(1.0);
  noStroke();
 
  shaderTexture = createGraphics(displayWidth,displayHeight, WEBGL);
  //shaderTexture = createGraphics(1280/2,720/2, WEBGL);
  shaderTexture.noStroke();
  shaderTexture.pixelDensity(1.0);
	
	// audio input (microphone)
	mic = new p5.AudioIn();
	mic.stop();

  console.log('width:'+width+' height:'+height);
}

function draw() {
	background(0);
	if (fullscreen()) {
		shaderTexture.textureMode(NORMAL);
		shaderTexture.textureWrap(REPEAT);
		noStroke();
		if (time < 220.0) {
		  theShader.setUniform('resolution', [width, height]);
		  //theShader.setUniform('mouse', [mouseX/width, mouseY/height]);
		  theShader.setUniform('mouse', [yokeX, yokeY]);
		  theShader.setUniform('yoke', [yokeX, yokeY]);
		  theShader.setUniform('time', time);
		  theShader.setUniform('back', shaderTexture);
		  theShader.setUniform('background', img);
		  shaderTexture.shader(theShader);
		  shaderTexture.rect(0,0,width, height);
		}
		texture(shaderTexture);
		rect(-width/2,-height/2,width, height);
		time += deltaTime/1000.0;
	}
	else {
		fill(255,255,255,255);
		textSize(16.0);
		textFont(myFont);
		//text('Click to start',-width/2,-height/2+16.0);
		text('Click to start',-width/2,-height/2+16.0);
		//if (mySound.isPlaying())
		//   mySound.stop();

	}
}
