const MAX_METEORS = 35;
const FONT_SIZE = 24;

const WEAPON = {
  LASER: 1,
  DUAL_LASER: 2,
  FREEZE_GUN: 3
};

const POWERUP = {
  DUAL_LASER: 1,
  FREEZE_ALL: 2,
  DOUBLE_POINTS: 3,
  FREEZE_GUN: 4
};

const METEOR_STATE = {
  NORMAL: 1,
  FROZEN: 2
};

class Scene2 extends Phaser.Scene {
  constructor() {
    super("playGame");


  }

  /*
  TODOs

  Update the first scene to make the menu better. Popup a new scene that displays the stats for that catechism set.
  Like number of questions, high scores, fastest time, etc.
  Allow the player to choose their ship color.

  Add sounds!

  Power Up Ideas
  Drone that floats around and holds meteors in a tractor beam to make it easier for you to shoot them. (if you shoot the drone, it is destroyed)
  One that destroys all the meteors on the screen. (green star)
  A drone like above, but a smart drone which goes to and holds the meteor that contains the next answer.

  Graphic Ideas
  Add a timer, get bonus points for a fast time.

  Add muzzle flash.

  Add gun turret.

  Gameplay Ideas.

  Add a break round where they just destroy a bunch of meteors. Can also add enemy ships that shoot at them during this "free play" round.

  Bonus points for the meteor being close to the bottom of the screen.

  Weapon Ideas:
  A swirling effect around the laser (like a rail gun trail).

  Explosion Ideas:
  Shrink the meteor into a single point then big explosion with halo effect ring.

  Technical
  Read more about scale manager and add a full screen mode.
  */

  saveState() {
    let saveRecord = {
        score: this.score,
        questionSet: config.questionSet,
        questionNum: this.curCatQuestion.num,
        weapon: this.playerShip.weapon
    };
    localStorage.setItem('saveRecord',JSON.stringify(saveRecord));
  }

  loadState() {
    let saveState = JSON.parse(localStorage.getItem('saveRecord'));

    if (saveState != null) {
      config.questionSet = saveState.questionSet;
    }

    return saveState;
  }

  create() {
    let savedState = this.loadState();
    this.score = savedState != null ? savedState.score : 0;
    // flawless means that you shot each word in order without hitting any wrong word.
    this.flawless = true;
    // excellent means that you shot each word before any words went off the bottom of the screen.
    this.excellent = true;
    this.scoreMultiplier = 1;

    this.background = this.add.tileSprite(0,0,config.width,config.height,"background");
    this.background.setOrigin(0,0);

    this.meteors = this.physics.add.group();

    for (let i=0; i<MAX_METEORS; i++) {
      let imageIndex = Phaser.Math.Between(1,4);
      let meteor = this.physics.add.image(0,0, "meteorBrown_big" + imageIndex);
      this.meteors.add(meteor);

      meteor.setCollideWorldBounds(true); // the world bounds (different than default) are defined in game.js.
      meteor.setBounce(1); // a value of one means that no speed is lost on impact.
      meteor.setImmovable(false);
      meteor.setVelocity(0, 50);
      meteor.state = METEOR_STATE.NORMAL;

      meteor.catText = this.add.bitmapText(20,20,'atari', 'test', FONT_SIZE*0.75);
      meteor.catText.setVisible(false);

      // this meteor is disabled as a physica body and graphic
      meteor.disableBody(true, true);

      // this enables input (on click)
      meteor.setInteractive();
      this.input.on('gameobjectdown', this.clickMeteor, this);
    }

    // make the meteors collide with each other.
    this.physics.add.collider(this.meteors, this.meteors);

    this.anims.create({
      key: "explodeSmoke",
      frames: this.anims.generateFrameNumbers("explosionSmoke"),
      frameRate: 20,
      repeat: 0,
      hideOnComplete: true
    });

    //this.explosion = this.add.sprite(-50, -50, "explosionSmoke");

    this.emitter_fragment1 = this.add.particles('meteorBrown_med1').createEmitter({
        x: 400,
        y: 300,
        speed: { min: -400, max: 400 },
        angle: { min: 0, max: 360 },
        scale: { start: 1, end: 0 },
        //blendMode: 'ADD',
        //active: false,
        // setting the frequency to -1 puts this emitter in explode mode.
        frequency: -1,
        lifespan: 600,
        gravityY: 0
    });
    this.emitter_explosion1 = this.add.particles('spark_orange').createEmitter({
        x: 400,
        y: 300,
        speed: { min: -800, max: 800 },
        angle: { min: 0, max: 360 },
        scale: { start: 0.7, end: 0 },
        blendMode: 'SCREEN',
        //active: false,
        frequency: -1,
        lifespan: 400,
        gravityY: 0
    });

    this.emitter_fragment2 = this.add.particles('meteorBrown_med1').createEmitter({
        x: 400,
        y: 300,
        speed: { min: -800, max: 800 },
        angle: { min: 0, max: 360 },
        scale: { start: 1, end: 0 },
        //blendMode: 'ADD',
        //active: false,
        // setting the frequency to -1 puts this emitter in explode mode.
        frequency: -1,
        lifespan: 900,
        gravityY: 0
    });
    this.emitter_explosion2 = this.add.particles('spark_red').createEmitter({
        x: 400,
        y: 300,
        speed: { min: -500, max: 500 },
        angle: { min: 0, max: 360 },
        scale: { start: 0.7, end: 0 },
        blendMode: 'SCREEN',
        //active: false,
        frequency: -1,
        lifespan: 600,
        gravityY: 0
    });

    this.emitter_fragment_frozen = this.add.particles('meteorGrey_med1').createEmitter({
        x: 400,
        y: 300,
        speed: { min: -800, max: 800 },
        angle: { min: 0, max: 360 },
        scale: { start: 1, end: 0 },
        frequency: -1,
        lifespan: 1000,
        gravityY: 0
    });
    this.emitter_explosion_frozen = this.add.particles('spark_blue').createEmitter({
        x: 400,
        y: 300,
        speed: 400,
        angle: { min: 0, max: 360, steps:32 },
        scale: { start: 0.7, end: 0 },
        quantity: 32,
        blendMode: 'SCREEN',
        frequency: -1,
        lifespan: 1000,
        gravityY: 0
    });

    this.emitter_sparks = this.add.particles('spark_orange').createEmitter({
        x: 400,
        y: 300,
        speed: { min: -800, max: 800 },
        angle: { min: 0, max: 360 },
        scale: { start: 0.3, end: 0 },
        blendMode: 'SCREEN',
        //active: false,
        frequency: -1,
        lifespan: 300,
        gravityY: 0
    });
    this.emitter_sparks_frozen = this.add.particles('spark_blue').createEmitter({
        x: 400,
        y: 300,
        speed: { min: -800, max: 800 },
        angle: { min: 0, max: 360 },
        scale: { start: 0.3, end: 0 },
        blendMode: 'SCREEN',
        //active: false,
        frequency: -1,
        lifespan: 300,
        gravityY: 0
    });

    //this.scoreText = this.add.text(config.width-40,config.height - 20,"Score: " + this.score, {font: "25px Verdana", fill: "white"}).setOrigin(1);
    this.scoreText = this.add.bitmapText(config.width-40,config.height - 20,"kenvector_thin", "Score: " + this.score, FONT_SIZE).setOrigin(1);

    // TODO should have a better way to name the weapon since this is repeated downstairs.
    let weaponName = "Laser";
    if (savedState != null) {
      if (savedState.weapon == WEAPON.DUAL_LASER) {
        weaponName = "DUAL LASER";
      } else if (savedState.weapon == WEAPON.FREEZE_GUN) {
        weaponName = "FREEZE";
      }
    }
    this.weaponText = this.add.bitmapText(40, config.height-20, 'kenvector_thin', weaponName, FONT_SIZE).setOrigin(0,1);
    this.questionStatusText = this.add.bitmapText(config.width / 2,config.height-20, 'kenvector_thin', "", FONT_SIZE).setOrigin(0.5,1);

    if (config.questionSet == 1) {
      this.catQuestions = [
      {num: 1, question: "Who made you?", answer: ["God","made","me"]},
      {num: 2, question: "What else did God make?", answer: ["God","made","all","things"]},
      {num: 3, question: "Why did God make you and all things?", answer: ["God","made","me","and","all","things","for","his","own","glory"]},
      {num: 4, question: "How can you glorify God?", answer: ["I","can","glorify","God","by","loving","him","and","doing","what","he","says"]},
      {num: 5, question: "Why should you glorify God?", answer: ["I","should","glorify","God","because","he","made","me","and","takes","care","of","me"]},
      {num: 6, question: "Is there more than one god?", answer: ["There","is","only","one","God"]},
      {num: 7, question: "In how many persons does this one God exist?", answer: ["God","exists","in","three","persons"]},
      {num: 8, question: "Who are they?", answer: ["The","Father,","the","Son","and","the","Holy","Spirit"]},
      {num: 9, question: "What is God?", answer: ["God","is","a","Spirit,","and","does","not","have","a","body","like","man"]},
      {num: 10, question: "Where is God?", answer: ["God","is","everywhere"]},
      {num: 11, question: "Can you see God?", answer: ["No.","I","cannot","see","God,","but","he","always","sees","me"]},
      {num: 12, question: "Does God know all things?", answer: ["Yes.","Nothing","can","be","hidden","from","God"]},
      {num: 13, question: "Can God do all things?", answer: ["Yes.","God","can","do","all","his","holy","will"]},
      {num: 14, question: "Where do you learn how to love and obey God?", answer: ["We","learn","to","love","and","obey","God","from","the","Bible","alone"]},
      {num: 15, question: "Who wrote the Bible?", answer: ["God","let","holy","men","who","were","taught","by","the","Holy","Spirit","write","the","Bible"]},
      {num: 16, question: "Who were our first parents?", answer: ["Adam","and","Eve","were","our","first","parents"]},
      {num: 17, question: "Of what were our first parents made?", answer: ["God","made","Adam","from","the","dust","of","the","ground,","and","formed","Eve","from","the","body","of","Adam"]},
      {num: 18, question: "What did God give Adam and Eve besides bodies?", answer: ["God","gave","Adam","and","Eve","souls","that","could","never","die"]},
      {num: 19, question: "Do you have a soul as well as a body?", answer: ["Yes.","I","have","a","soul","that","can","never","die"]},
      {num: 20, question: "What is your soul?", answer: ["My","soul","includes","all","of","me","that","should","know","and","love","God"]},
      {num: 21, question: "In what condition did God make Adam and Eve?", answer: ["God","made","Adam","and","Eve","holy","and","happy"]},
      {num: 22, question: "Did Adam and Eve stay holy and happy?", answer: ["No.","They","sinned","against","God"]},
      {num: 23, question: "What was the sin of our first parents?", answer: ["They","sinned","against","God","by","eating","the","forbidden","fruit"]},
      {num: 24, question: "Why did they eat the forbidden fruit?", answer: ["They","ate","the","forbidden","fruit","because","they","did","not","believe","what","God","had","said"]},
      {num: 25, question: "Who tempted them to this sin?", answer: ["Satan","tempted","Eve,","and","she","gave","the","fruit","to","Adam"]},
      {num: 26, question: "What happened to our first parents when they sinned?", answer: ["Instead","of","being","holy","and","happy,","they","became","sinful","and","miserable"]},
      {num: 27, question: "What effect did the sin of Adam have on all people?", answer: ["All","people","are","born","in","a","state","of","sin","and","misery"]},
      {num: 28, question: "What do we inherit from Adam as a result of original sin?", answer: ["A","sinful","nature"]},
      {num: 29, question: "What is sin?", answer: ["Sin","is","failing","to","do","what","God","commands"]},
      {num: 30, question: "In what ways do we sin?", answer: ["We","sin","in","thought,","word","and","deed"]},
      {num: 31, question: "What does every sin deserve?", answer: ["Every","sin","deserves","the","anger","and","punishment","of","God"]},
      {num: 32, question: "Do we know what God requires of us?", answer: ["Yes.","He","has","given","us","his","law","both","in","our","hearts","and","in","writing"]},
      {num: 33, question: "Can anyone go to heaven with this sinful nature?", answer: ["No.","Our","hearts","must","be","changed","before","we","can","be","fit","for","heaven"]},
      {num: 34, question: "What is a change of heart called?", answer: ["Regeneration","is","a","change","of","heart","that","leads","to","true","repentance","and","faith"]},
      {num: 35, question: "Who can change a sinner's heart?", answer: ["Only","the","Holy","Spirit","can","change","a","sinner's","heart"]},
      {num: 36, question: "What is God's righteousness?", answer: ["God's","righteousness","means","that","God","always","does","what","is","right","and","is","the","final","standard","of","what","is","right"]},
      {num: 37, question: "Can anyone be saved by his own righteousness?", answer: ["No.","No","one","is","good","enough","before","God"]}
    ];
    } else if (config.questionSet == 2) {
      this.catQuestions = [
      {num: 1, question: "What is a covenant?", answer: ["A","covenant","is","an","agreement","between","two","or","more","people"]},
      {num: 2, question: "What is the new covenant?", answer: ["The","new","covenant","is","the","agreement","God","made","with","his","elect","people","to","save","them","from","their","sins"]},
      {num: 3, question: "What did Christ undertake in the new covenant?", answer: ["To","keep","the","whole","law","for","his","people","and","to","suffer","the","punishment","due","for","their","sins"]},
      {num: 4, question: "What did God the Father undertake in the new covenant?", answer: ["To","justify","and","sanctify","those","for","whom","Christ","should","die"]},
      {num: 5, question: "Did our Lord Jesus Christ ever commit a sin?", answer: ["No.","He","was","holy","and","without","sin"]},
      {num: 6, question: "How could the Son of God suffer the anger and judgment of God?", answer: ["Christ,","the","son","of","God,","became","a","man,","that","he","might","obey","and","suffer","as","a","man"]},
      {num: 7, question: "What is election?", answer: ["Election","is","God's","goodness","revealed","in","his","grace","by","choosing","certain","sinners","for","salvation"]},
      {num: 8, question: "What is adoption?", answer: ["Adoption","is","God's","goodness","in","bringing","repentant","sinners","into","his","own","family","and","treating","them","as","his","beloved","children"]},
      {num: 9, question: "How do you know that you are God's child?", answer: ["I","know","that","I'm","God's","child","because","the","Holy","Spirit","assures","me","and","enables","me","to","love","God","and","other","people"]},
      {num: 10, question: "What is the atonement?", answer: ["The","atonement","is","Christ","satisfying","divine","justice,","by","his","sufferings","and","death","in","the","place","of","sinners"]},
      {num: 11, question: "What is justification?", answer: ["Justification","is","God","forgiving","sinners","and","viewing","them","as","righteous","because","they","are","in","Christ"]},
      {num: 12, question: "How can we be justified?", answer: ["We","can","be","justified","only","by","trusting","in","Christ","to","take","away","our","sins"]},
      {num: 13, question: "What is sanctification?", answer: ["Sanctification","is","God","making","sinners","holy","in","heart","and","conduct","so","that","they","will","demonstrate","his","goodness","in","their","lives"]},
      {num: 14, question: "Is this process of sanctification ever complete in life?", answer: ["No.","Sanctification","is","certain","and","continual,","but","is","complete","only","in","heaven"]},
      {num: 15, question: "What connection is there between justification and sanctification?", answer: ["Both","justification","and","sanctification","arise","out","of","a","union","with","Christ"]},
      {num: 16, question: "For whom did Christ obey the law and suffer the anger and judgment of God?", answer: ["Christ","obeyed","the","law","and","suffered","the","anger","and","judgment","of","God","for","those","whom","the","Father","had","given","him"]},
      {num: 17, question: "What kind of life did Christ live on earth?", answer: ["Christ","lived","a","life","of","perfect","obedience","to","the","law","of","God"]},
      {num: 18, question: "What kind of death did Christ die?", answer: ["Christ","experienced","the","painful","and","shameful","death","of","the","cross"]},
      {num: 19, question: "How can you be saved?", answer: ["If","you","repent","of","your","sin","and","believe","in","Christ,","you","will","be","saved"]},
      {num: 20, question: "What does it mean to repent?", answer: ["To","repent","means","to","be","sorry","for","sin,","and","to","hate","and","reject","it","because","it","is","displeasing","to","God"]},
      {num: 21, question: "What does it mean to believe or have faith in Christ?", answer: ["A","person","who","believes","in","Christ","trusts","him","alone","for","salvation"]},
      {num: 22, question: "Can you repent and believe in Christ by your own power?", answer: ["No.","I","can","do","nothing","good","without","God's","Holy","Spirit"]},
      {num: 23, question: "How can you receive the Holy Spirit?", answer: ["God","has","told","us","that","we","must","pray","to","him","for","the","Holy","Spirit,","but","the","evidence","of","his","presence","is","seen","most","clearly","in","our","trusting","and","loving","the","Lord","Jesus","Christ"]},
      {num: 24, question: "How does the Holy Spirit baptize believers?", answer: ["The","Holy","Spirit","puts","them","into","the","body","of","Christ","by","making","them","a","living","part","of","all","those","who","truly","believe","in","him"]},
      {num: 25, question: "How does the Holy Spirit seal believers?", answer: ["The","Holy","Spirit","comes","to","live","within","them","to","guarantee","that","they","will","receive","the","riches","God","has","promised","for","those","who","love","him"]},
      {num: 26, question: "How were godly persons saved before the coming of Christ?", answer: ["They","believed","in","the","promise","of","God"]},
      {num: 27, question: "How did they show their faith?", answer: ["They","offered","sacrifices","according","to","God's","commands"]},
      {num: 28, question: "What did these sacrifices represent?", answer: ["These","sacrifices","represent","Christ,","the","Lamb","of","God,","who","was","to","die","for","sinners"]},
      {num: 29, question: "What does Christ do for his people?", answer: ["Christ","does","the","work","of","a","prophet,","a","priest","and","a","king"]},
      {num: 30, question: "How is Christ our Prophet?", answer: ["Christ","teaches","us","the","will","of","God,","reveals","God","to","us,","and","really","was","God","in","human","flesh"]},
      {num: 31, question: "Why do you need Christ as Prophet?", answer: ["I","need","Christ","as","Prophet","because","I","lack","understanding"]},
      {num: 32, question: "How is Christ our Priest?", answer: ["Christ","died","for","our","sins","and","pleads","with","God","for","us"]},
      {num: 33, question: "Why do you need Christ as Priest?", answer: ["I","need","Christ","as","Priest","because","I","am","guilty"]},
      {num: 34, question: "How is Christ our King?", answer: ["Christ","rules","over","us","and","defends","us"]},
      {num: 35, question: "Why do you need Christ as King?", answer: ["I","need","Christ","as","King","because","I","am","weak","and","helpless"]}
    ];
    } else if (config.questionSet == 3) {
      this.catQuestions = [
        {num: 1, question: "How many commandments did God give on Mt. Sinai?", answer: ["God","gave","ten","commandments","on","Mt.","Sinai"]},
  {num: 2, question: "What do the first four commandments teach?", answer: ["The","first","four","commandments","teach","our","duty","to","God"]},
  {num: 3, question: "What do the last six commandments teach?", answer: ["The","last","six","commandments","teach","our","duty","to","our","fellow","men"]},
  {num: 4, question: "What is the sum of the Ten Commandments?", answer: ["The","sum","of","the","ten","commandments","is","to","love","God","with","all","my","heart","and","my","neighbor","as","myself"]},
  {num: 5, question: "Who is your neighbor?", answer: ["Everyone","is","my","neighbor"]},
  {num: 6, question: "Is God pleased with those who love and obey him?", answer: ["Yes.","God","is","pleased","with","those","who","love","and","obey","him"]},
  {num: 7, question: "Is God displeased with those who do not love and obey him?", answer: ["Yes.","God","is","displeased","with","those","who","do","not","love","and","obey","him"]},
  {num: 8, question: "What is the first commandment?", answer: ["You","shall","have","no","other","gods","before","me"]},
  {num: 9, question: "What does the first commandment teach us?", answer: ["To","worship","only","God"]},
  {num: 10, question: "What is the second commandment?", answer: ["Do","not","make","idols","or","worship","them"]},
  {num: 11, question: "What does the second commandment teach us?", answer: ["To","worship","God","in","the","right","way","and","to","not","worship","idols"]},
  {num: 12, question: "What is the third commandment?", answer: ["Do","not","use","the","name","of","God","carelessly"]},
  {num: 13, question: "What does the third commandment teach us?", answer: ["To","honor","and","respect","God's","name,","word","and","works"]},
  {num: 14, question: "What is the fourth commandment?", answer: ["Remember","the","Sabbath","and","keep","it","holy"]},
  {num: 15, question: "What does the fourth commandment teach us?", answer: ["To","rest","in","Christ","alone","for","salvation"]},
  {num: 16, question: "What day of the week is the Lord's Day?", answer: ["The","first","day","of","the","week,","called","the","Lord's","Day"]},
  {num: 17, question: "Why is it called the Lord's Day?", answer: ["It","is","called","the","Lord's","Day","because","on","that","day","Christ","rose","from","the","dead"]},
  {num: 18, question: "How should the Lord's Day be kept?", answer: ["The","Lord's","Day","should","be","kept","in","prayer","and","praise,","in","hearing","and","reading","God's","word,","and","in","doing","good","to","my","neighbors"]},
  {num: 19, question: "What is the fifth commandment?", answer: ["Honor","your","father","and","mother"]},
  {num: 20, question: "What does the fifth commandment teach us?", answer: ["To","love","and","obey","our","parents"]},
  {num: 21, question: "What is the sixth commandment?", answer: ["Do","not","murder"]},
  {num: 22, question: "What does the sixth commandment teach us?", answer: ["To","avoid","hatred,","all","that","leads","to","it,","and","all","that","follows","from","it"]},
  {num: 23, question: "What is the seventh commandment?", answer: ["Do","not","commit","adultery"]},
  {num: 24, question: "What does the seventh commandment teach us?", answer: ["To","be","sexually","pure","in","thought,","word","and","deed"]},
  {num: 25, question: "What is the eighth commandment?", answer: ["Do","not","steal"]},
  {num: 26, question: "What does the eighth commandment teach us?", answer: ["To","be","honest","and","not","to","take","the","things","of","others"]},
  {num: 27, question: "What is the ninth commandment?", answer: ["Do","not","lie"]},
  {num: 28, question: "What does the ninth commandment teach us?", answer: ["To","tell","the","truth","and","not","to","speak","evil","of","others"]},
  {num: 29, question: "What is the tenth commandment?", answer: ["Do","not","covet"]},
  {num: 30, question: "What does the tenth commandment teach us?", answer: ["To","be","content","with","what","we","have"]},
  {num: 31, question: "Can anyone keep the Ten Commandments perfectly?", answer: ["Nobody","since","the","fall","of","Adam,","except","Jesus,","ever","did","or","can","keep","the","Ten","Commandments","perfectly"]},
  {num: 32, question: "Of what use are the Ten Commandments to us?", answer: ["They","teach","us","our","duty,","and","show","us","our","guilt","and","need","of","a","Savior"]}
  ];
    } else if (config.questionSet == 4) {
      this.catQuestions = [
        {num: 1, question: "What is prayer?", answer: ["Prayer","is","talking","with","God"]},
    {num: 2, question: "In whose name should we pray?", answer: ["We","should","pray","in","the","name","of","the","Lord","Jesus","Christ"]},
    {num: 3, question: "What has Christ given to teach us how to pray?", answer: ["The","Lord's","Prayer"]},
    {num: 4, question: "How many requests are there in the Lord's Prayer?", answer: ["Six"]},
    {num: 5, question: "What is the first request?", answer: ["Hallowed","be","your","name"]},
    {num: 6, question: "What do we pray for in the first request?", answer: ["That","God's","name","may","be","honored","by","us","and","all","people"]},
    {num: 7, question: "What is the second request?", answer: ["Your","kingdom","come"]},
    {num: 8, question: "What do we pray for in the second request?", answer: ["That","the","gospel","may","be","preached","to","the","entire","world,","and","believed","and","obeyed","by","us","and","all","people"]},
    {num: 9, question: "What is the third request?", answer: ["Your","will","be","done","on","earth,","as","it","is","in","heaven"]},
    {num: 10, question: "What do we pray for in third request?", answer: ["That","people","on","earth","may","serve","God","as","the","angels","do","in","heaven"]},
    {num: 11, question: "What is the fourth request?", answer: ["Give","us","this","day","our","daily","bread"]},
    {num: 12, question: "What do we pray for in the fourth request?", answer: ["That","God","will","give","us","everything","we","need","for","our","bodies","and","souls"]},
    {num: 13, question: "What is the fifth request?", answer: ["And","forgive","us","our","debts,","as","we","forgive","our","debtors"]},
    {num: 14, question: "What do we pray for in the fifth request?", answer: ["That","God","would","pardon","our","sins","for","Christ's","sake,","and","enable","us","to","forgive","those","who","have","sinned","against","us"]},
    {num: 15, question: "What is the sixth request?", answer: ["And","lead","us","not","into","temptation,","but","deliver","us","from","evil"]},
    {num: 16, question: "What do we pray for in the sixth request?", answer: ["That","God","will","keep","us","from","sin"]},{num: 17, question: "What does prayer teach us?", answer: ["Our","complete","dependence","on","God"]}
    ];
    } else if (config.questionSet == 5) {
      this.catQuestions = [
        {num: 1, question: "How does the Holy Spirit bring us salvation?", answer: ["He","uses","the","Bible,","which","is","the","Word","of","God"]},
        {num: 2, question: "How can we know the Word of God?", answer: ["We","are","commanded","to","hear,","read","and","search","the","Scriptures"]},
        {num: 3, question: "What is a church?", answer: ["A","church","is","an","assembly","of","baptized","believers","joined","by","a","covenant","of","discipline","and","witness","who","meet","together","regularly","under","the","preaching","of","the","Word","of","God"]},
        {num: 4, question: "What two ordinances did Christ give the church?", answer: ["Baptism","and","the","Lord's","Supper"]},
        {num: 5, question: "Why did Christ give these ordinances?", answer: ["To","show","that","his","disciples","belong","to","him,","and","to","remind","them","of","what","he","has","done","for","them"]},
        {num: 6, question: "What is baptism?", answer: ["Baptism","is","the","dipping","of","believers","into","water,","as","a","sign","of","their","union","with","Christ","in","his","death,","burial","and","resurrection"]},
        {num: 7, question: "What does baptism represent?", answer: ["Baptism","represents","to","believers","that","God","has","cleansed","them","from","their","sins","through","Jesus","Christ"]},
        {num: 8, question: "Who are the be baptized?", answer: ["Only","those","who","repent","of","their","sins,","and","believe","in","Christ","for","salvation","should","be","baptized"]},
        {num: 9, question: "Should babies be baptized?", answer: ["Only","those","who","give","a","credible","profession","of","faith","in","Christ","should","be","baptized"]},
        {num: 10, question: "Does Christ welcome little children?", answer: ["Yes.","He","invites","little","children","to","come","to","him","by","faith"]},
        {num: 11, question: "What is the Lord's Supper?", answer: ["At","the","Lord's","Supper,","the","church","eats","bread","and","drinks","wine","to","remember","the","sufferings","and","death","of","our","Lord","Jesus","Christ"]},
        {num: 12, question: "What does the bread represent?", answer: ["The","bread","represents","the","body","of","Christ,","broken","for","our","sins"]},
        {num: 13, question: "What does the wine represent?", answer: ["The","wine","represents","the","blood","of","Christ,","shed","for","our","salvation"]},
        {num: 14, question: "Who should partake of the Lord's Supper?", answer: ["The","Lord's","Supper","is","for","those","only","who","repent","of","their","sins,","believe","in","Christ","for","salvation,","receive","baptism","and","love","one","another"]}
      ];
    } else if (config.questionSet == 6) {
      this.catQuestions = [
        {num: 1, question: "Did Christ remain in the tomb after his crucifixion?", answer: ["No.","He","rose","from","the","tomb","the","third","day","after","his","death"]},
    {num: 2, question: "Where is Christ now?", answer: ["Christ","is","in","heaven,","seated","at","the","right","hand","of","God","the","Father"]},
    {num: 3, question: "Will Christ come again?", answer: ["Yes.","At","the","last","day","he","will","come","to","judge","the","world"]},
    {num: 4, question: "What happens to men when they die?", answer: ["The","body","returns","to","dust,","and","the","soul","goes","to","be","with","God","or","to","a","place","of","suffering","that","awaits","the","resurrection","for","judgment"]},
    {num: 5, question: "Will the bodies of the dead be raised to life again?", answer: ["Yes.","There","will","be","a","resurrection","of","the","dead,","both","of","the","righteous","and","the","wicked"]},
    {num: 6, question: "What will happen to the wicked in the Day of Judgment?", answer: ["They","shall","be","cast","into","hell"]},
    {num: 7, question: "What is hell?", answer: ["Hell","is","a","place","of","dreadful","and","endless","punishment"]},
    {num: 8, question: "What will happen to the righteous on the Day of Judgment?", answer: ["They","will","live","with","Christ","forever,","in","a","new","heaven","and","new","earth"]},
    {num: 9, question: "In the light of these truths, what should you do?", answer: ["I","should","strive","with","all","my","energy","to","believe","in","the","Lord","Jesus","Christ","and","repent","of","my","sin"]},
    {num: 10, question: "What is the gospel?", answer: ["Holy","God,","in","love","became","perfect","man","to","bear","my","blame,","on","the","cross","he","took","my","sin","and","by","his","death","I","live","again"]}
    ];
    } else {
      this.catQuestions = [
      {num: 1, question: "What did Christ undertake in the new covenant?", answer: ["To"]}
      //  {num: 2, question: "What did Christ undertake in the new covenant?", answer: ["To","keep","the","whole","law","for","his","people","and","to","suffer","the","punishment","due","for","their","sins"]}
      ];
    }

    let questionIndex = savedState != null ? (savedState.questionNum-1) : 0;

    this.curCatQuestion = {
      num: this.catQuestions[questionIndex].num,
      question: this.catQuestions[questionIndex].question,
      answer: this.catQuestions[questionIndex].answer,
      answerIndex: 0
    };

    //this.questionText = this.add.text(20,20,this.curCatQuestion.num + ". " + this.curCatQuestion.question, {font: "20px Arial", fill: "yellow"});
    //this.answerText = this.add.text(20,50,"", {font: "20px Arial", fill: "yellow"});
    this.answerText = this.add.bitmapText(config.width / 2, 50, 'atari', "", FONT_SIZE);
    this.answerText.setOrigin(0.5);
    this.answerText.setCenterAlign();
    //this.answerText.setMaxWidth(config.width - 50);

    this.questionText = this.add.bitmapText(0, 0, 'atari', this.curCatQuestion.question, FONT_SIZE);
    this.wrapText(this.questionText);
    this.questionText.setOrigin(0.5);
    this.questionText.setPosition(config.width / 2, config.height / 2);
    this.questionText.setCenterAlign();

    this.questionStatusText.setText(this.curCatQuestion.num + " of " + this.catQuestions.length);

    //this.questionText.setMaxWidth(config.width - 50);

    var tween = this.tweens.add({
        targets: this.questionText,
        props: {
            scale: { from: 0, to: 1, duration: 1000, ease: 'Back.easeOut' },
            scaleX: { value: 0.5, duration: 500, delay: 1500, ease: 'Linear'},
            scaleY: { value: 0.5, duration: 500, delay: 1500, ease: 'Linear'},
            y: {value: 20, duration: 500, ease: 'Linear', delay: 1500}
        },
        callbackScope: this,
        onComplete: function() { this.initMeteors(); }
    });

    // add the player player ship.
    this.playerShip = this.physics.add.image(config.width / 2, config.height - 100, "playerShip1_blue");
    this.playerShip.setOrigin(0.5);
    this.playerShip.setInteractive({draggable: true});
    this.playerShip.setCollideWorldBounds(true);
    this.playerShip.on('drag', function(pointer, dragX, dragY){ this.playerShip.x = dragX; }, this);
    this.playerShip.setName('PlayerShip');
    this.playerShip.weapon = savedState != null ? savedState.weapon : WEAPON.LASER;

    // test follower
    /*
    let points = [
        50, -100, 50, 300, 179, 449, 394, 498, 593, 455,
        701, 338, 692, 190, 603, 76, 423, 41,
        272, 78, 181, 186, 230, 328, 416, 395,
        565, 327, 550, 202, 467, 149, 355, 164,
        343, 254, 428, 303
    ];

    let curve = new Phaser.Curves.Spline(points);

    for (let i = 0; i < 4; i++)
    {
        let follower = this.add.follower(curve, 100 + (200 * i), -100, 'enemyRed1');

        //follower.setScale(0.5);
        //follower.setBlendMode(Phaser.BlendModes.ADD);
        follower.setInteractive();

        follower.startFollow({
            duration: 6000,
            yoyo: true,
            repeat: -1,
            ease: 'Sine.easeInOut',
            //ease: 'Linear',
            //_delay: i * 200,
            delay: i * 100
        });
    }
    */
  }

  spawnPowerup(powerupType) {
    // add a powerup
    var powerUp;
    switch (powerupType || Phaser.Math.Between(1,4)) {
    case 1:
      powerUp = this.physics.add.image(Phaser.Math.Between(50, config.width-50),-50, "powerupGreen_bolt");
      powerUp.powerUpType = POWERUP.DUAL_LASER;
      break;
    case 2:
      powerUp = this.physics.add.image(Phaser.Math.Between(50, config.width-50),-50, "powerupBlue_star");
      powerUp.powerUpType = POWERUP.FREEZE_ALL;
      break;
    case 3:
      powerUp = this.physics.add.image(Phaser.Math.Between(50, config.width-50),-50, "star_silver");
      powerUp.powerUpType = POWERUP.DOUBLE_POINTS;
      break;
    case 4:
      powerUp = this.physics.add.image(Phaser.Math.Between(50, config.width-50),-50, "powerupBlue_bolt");
      powerUp.powerUpType = POWERUP.FREEZE_GUN;
      break;
    }

    powerUp.setVelocity(Phaser.Math.Between(-70,70), Phaser.Math.Between(200,250));
    // if we hit the lower world bounds, then we will destoy the powerup so it doesn't bounce back up!
    powerUp.setCollideWorldBounds(true);
    powerUp.body.onWorldBounds = true;
    this.physics.world.on('worldbounds', function(body){
        if (body.y > config.height) {
          body.destroy();
        }
    },this);
    powerUp.setBounce(1);

    this.physics.add.overlap(powerUp, this.playerShip, this.collectPowerup, null, this);
  }

  collectPowerup(powerUp, player) {
    if (powerUp.powerUpType == POWERUP.DUAL_LASER) {
      player.weapon = WEAPON.DUAL_LASER;
      this.weaponText.setText('DUAL LASER');
      powerUp.destroy();
    } else if (powerUp.powerUpType == POWERUP.FREEZE_GUN) {
      player.weapon = WEAPON.FREEZE_GUN;
      this.weaponText.setText('FREEZE');
      powerUp.destroy();
    } else if (powerUp.powerUpType == POWERUP.FREEZE_ALL) {
      let mets = this.meteors.getChildren();
      for (let i=0; i<MAX_METEORS; i++) {
        if (mets[i].active) {
          this.freezeMeteor(mets[i]);
        }
      }
      powerUp.destroy();
    } else if (powerUp.powerUpType == POWERUP.DOUBLE_POINTS) {
      this.scoreMultiplier = this.scoreMultiplier * 2;

      // after 20 seconds, set the multiplier back to one.
      // we disable the physics on this powerup and keep it on the screen so we know how long this powerup lasts.
      powerUp.setVelocity(0,0);
      powerUp.disableBody();
      this.tweens.add({
          targets: powerUp,
          props: {
              y: {value: config.height - 40, duration: 500, ease: 'Back.easeOut' },
              x: {value: config.width * 0.8, duration: 500, ease: 'Back.easeOut'},
              alpha: {from: 1, to: 0.2, duration: 1000, ease: 'Elastic', delay: 19000}
          },
          callbackScope: this,
          //completeDelay: 20000,
          onComplete: function() { this.scoreMultiplier = this.scoreMultiplier * 0.5; powerUp.destroy(); }
        });
    }
  }

  fireLaser(x, y, x_to, y_to) {
    if (this.playerShip.weapon == WEAPON.DUAL_LASER) {
      var laser1 = this.add.line(0,0,x-this.playerShip.width/2,y+35,x_to,y_to,0xffcc00).setOrigin(0).setLineWidth(1);
      var laser2 = this.add.line(0,0,x+this.playerShip.width/2,y+35,x_to,y_to,0xffcc00).setOrigin(0).setLineWidth(1);

      var tween = this.tweens.add({
          targets: [laser1, laser2],
          props: {
              alpha: { from: 1, to: 0, duration: 500, ease: 'Elastic' }
          },
          callbackScope: this,
          onComplete: function() { laser1.destroy(); laser2.destroy(); }
        });

    } else if (this.playerShip.weapon == WEAPON.FREEZE_GUN) {
      var laser = this.add.line(0,0,x,y,x_to,y_to,0xb0e7ff).setOrigin(0).setLineWidth(2,1);

      var tween = this.tweens.add({
          targets: laser,
          props: {
              alpha: { from: 1, to: 0, duration: 800, ease: 'Elastic' }
          },
          callbackScope: this,
          onComplete: function() { laser.destroy(); }
        });
    } else {
      var laser = this.add.line(0,0,x,y,x_to,y_to,0x36bbf5).setOrigin(0);

      var tween = this.tweens.add({
          targets: laser,
          props: {
              alpha: { from: 1, to: 0, duration: 300, ease: 'Bounce' }
          },
          callbackScope: this,
          onComplete: function() { laser.destroy(); }
        });
    }
  }

  wrapText(textObj, fontSize) {
    // don't wrap if this text already fits the screen.
    if (textObj.width < config.width - 50) {
      return;
    }

    var text = textObj.text;
    var preText = "";
    var lastLine = "";

    // find the new line and start there.
    var index = text.lastIndexOf('\n');
    if (index > 0) {
      lastLine = text.slice(index);
      preText = text.slice(0, index + 1);
    } else {
      preText = "";
      lastLine = text;
    }

    // preText has previous line of the string.
    // lastLine has the last line (the too long line) or an only line of the string.
    // it is lastLine that we must shorten by inserting a new line.

    // assume FONT_SIZE for each letter if not provided.
    var lineMaxCharacters = (config.width-50) / (fontSize || FONT_SIZE);
    var words = lastLine.split(" ");
    var lineCharacters = 0;
    var newLine = '';

    for (let i = 0; i < words.length; i++) {
      // add up the number of characters in the line. The +1 is for the space that goes with this word.
      lineCharacters += words[i].length + 1;

      if (lineCharacters > lineMaxCharacters) {
        newLine += '\n';
        lineCharacters = 0;
      }

      newLine += ' ' + words[i];
    }

    textObj.setText(preText + newLine.trim());
  }

  initMeteors() {
    let mets = this.meteors.getChildren();
    // clone a copy of the answers array since we don't want to modify it
    let answers = this.curCatQuestion.answer.slice();
    Phaser.Utils.Array.Shuffle(answers);
    let numColumns = Math.floor(config.width / 120);
    let curColumn = 0;
    let curRow = 1;
    let minVelocity = 50;
    let maxVelocity = 150;
    if (answers.length > (numColumns * 2)) {
      minVelocity = 30;
      maxVelocity = 60;
    } else if (answers.length > numColumns) {
      maxVelocity = 90;
    }
    for (let i=0;i<this.curCatQuestion.answer.length;i++) {
      // enableBody turns on this game object and puts it in specified location.
      //mets[i].enableBody(true, Phaser.Math.Between(0, config.width), -mets[i].height * Phaser.Math.FloatBetween(1, 4), true, true);
      mets[i].enableBody(true, (curColumn * 120) + 60, -100 * curRow, true, true);
      mets[i].setVelocity(Phaser.Math.Between(-50,50), Phaser.Math.Between(minVelocity, maxVelocity));
      mets[i].setRotation(Phaser.Math.Between(0, 360));
      mets[i].setTexture("meteorBrown_big" + Phaser.Math.Between(1,4));
      mets[i].catText.setText(answers[i]);
      mets[i].catText.setVisible(true);
      mets[i].state = METEOR_STATE.NORMAL;

      curColumn++;
      if (curColumn == numColumns) {
        curColumn = 0;
        curRow++;
      }
    }
  }

  getNextAnswer() {
    return this.curCatQuestion.answer[this.curCatQuestion.answerIndex];
  }

  updateScore(increase) {
    // we don't keep score in Joshy mode.
    if (config.mode != MODE.JOSHY) {
      this.score = this.score + (increase * this.scoreMultiplier);
      this.scoreText.setText("Score: " + this.score);
    }

    if (increase < 0) {
      this.excellent = false;
      this.flawless = false;
    }
  }

  checkNextAnswer(text) {
    if (this.getNextAnswer() == text) {
      this.curCatQuestion.answerIndex++;

      if (this.answerText.text.length == 0) {
        this.answerText.setText(text);
      } else {
        this.answerText.setText(this.answerText.text + " " + text);
        this.wrapText(this.answerText);
      }
      return true;
    }
  }

  checkWordsComplete() {
    return this.curCatQuestion.answerIndex == this.curCatQuestion.answer.length;
  }

  transitionNextQuestion() {
    if (this.curCatQuestion.num < this.catQuestions.length) {
      this.curCatQuestion.question = this.catQuestions[this.curCatQuestion.num].question;
      this.curCatQuestion.answer = this.catQuestions[this.curCatQuestion.num].answer;
      this.curCatQuestion.num ++;
      this.curCatQuestion.answerIndex = 0;
    } else {
      // there are no more questions in this set.
      // transition to the next scene to end the game.
      this.time.addEvent({
        delay: 1000,
        callback: function() {
          config.score = this.score;
          this.scene.start("endGame");
        },
        callbackScope: this,
        loop: false
      });

      return;
    }

    this.answerText.setText("");
    this.answerText.scale = 1;
    this.answerText.setOrigin(0.5);
    this.answerText.setPosition(config.width / 2, 50);

    // set the question text and then setup a tween to animate it before it calls initMeteors();
    this.questionText.setText(this.curCatQuestion.question);

    // we have to set the scale to one before setting the origin and setting
    // the position so that the text is in the center of the screen.
    this.questionText.scale = 1;
    this.wrapText(this.questionText);
    this.questionText.setOrigin(0.5);
    this.questionText.setPosition(config.width / 2, config.height / 2);
    this.questionText.scale = 0;

    this.questionStatusText.setText(this.curCatQuestion.num + " of " + this.catQuestions.length);

    // create tween to bring the text to the proper scale.
    let tween = this.tweens.add({
        targets: this.questionText,
        props: {
            scale: { from: 0, to: 1, duration: 1000, ease: 'Back.easeOut' },
            scaleX: { value: 0.5, duration: 500, delay: 1500, ease: 'Linear'},
            scaleY: { value: 0.5, duration: 500, delay: 1500, ease: 'Linear'},
            y: {value: 20, duration: 500, ease: 'Linear', delay: 1500}
        },
        callbackScope: this,
        onComplete: function() {
          this.initMeteors();
          if (this.excellent) {
            this.spawnPowerup();
          }
          if (this.flawless) {
            this.spawnPowerup();
          }
          this.excellent = true;
          this.flawless = true;
        }
    });

    this.saveState();

  }

  moveMeteor(meteor) {
    // the meteor is automatically moved by Phaser using it's velocity/gravity, etc.

    // if the meteor is off the bottom of the screen, reset it and lose a point.
    if (meteor.y - meteor.height > config.height) {
      this.resetMeteorPosition(meteor);
      this.updateScore(-1);
    }

    // if the meteor has text, make that text position match the meteor's position.
    if (meteor.catText) {
      meteor.catText.setPosition(meteor.x - (meteor.catText.width / 2), meteor.y - (meteor.catText.height / 2));

      if (config.mode == MODE.JOSHY) {
        // check if this meteor holds the next answer.
        if (this.getNextAnswer() == meteor.catText.text) {
          if (!this.tweens.isTweening(meteor)) {
            this.tweens.add({
              targets: meteor,
              props: {
                //alpha: { from: 0.5, to: 1, duration: 500, yoyo: true, repeat: 4, ease: 'Linear'},
                tint: {from: 0xffffff, to:0xffff00, duration: 500, yoyo: true, repeat: 4, ease: 'Linear'},
                scale: { from: 1, to: 1.5, duration: 250, yoyo: true, repeat: 8, ease: 'Sine'}
              }
            });
          }
        }
      }
    }
  }

  resetMeteorPosition(meteor) {
    meteor.setPosition(Phaser.Math.Between(0, config.width), -meteor.height);
    meteor.setRotation(Phaser.Math.Between(0, 360));
    meteor.setVelocity(Phaser.Math.Between(-50,50), Phaser.Math.Between(50,150));

    // if this meteor is frozen, we "thaw" it out before it begins its next journey.
    if (meteor.state == METEOR_STATE.FROZEN) {
      meteor.setTexture("meteorBrown_big" + Phaser.Math.Between(1,4));
      meteor.state = METEOR_STATE.NORMAL;
    }
  }

  freezeMeteor(meteor) {
    meteor.setVelocity(0, 12);

    // we replace the brown texture with the grey one if this meteor is "frozen".
    // there are a number of textures and so we keep the same texture number.
    let curTextureKey = meteor.texture.key;
    if (meteor.state == METEOR_STATE.NORMAL && curTextureKey.indexOf("meteorBrown_big") > -1) {
      meteor.setTexture("meteorGrey_big" + curTextureKey.charAt(15));
      meteor.state = METEOR_STATE.FROZEN;
    }
  }

  clickMeteor(pointer, gameObject) {

    if (gameObject.name === 'PlayerShip') {
      return;
    }

    // draw laser beam
    this.fireLaser(this.playerShip.x, this.playerShip.y - (this.playerShip.height/2), pointer.x, pointer.y, this.playerShip);

    // check if this is this is the right answer
    if (gameObject.catText && gameObject.visible) {
      // if this is the right catechism answer...
      if (this.checkNextAnswer(gameObject.catText.text)) {
        // if this meteor is "frozen" we have another effect.
        if (gameObject.state == METEOR_STATE.FROZEN) {
          this.emitter_fragment_frozen.emitParticle(20, pointer.x, pointer.y);
          this.emitter_explosion_frozen.emitParticle(32, pointer.x, pointer.y);
        } else if (this.playerShip.weapon == WEAPON.DUAL_LASER) {
          this.emitter_fragment2.emitParticle(20, pointer.x, pointer.y);
          this.emitter_explosion2.emitParticle(40, pointer.x, pointer.y);
        } else {
          this.emitter_fragment1.emitParticle(10, pointer.x, pointer.y);
          this.emitter_explosion1.emitParticle(50, pointer.x, pointer.y);
        }

        gameObject.disableBody(true, true);
        gameObject.catText.setVisible(false);

        if (this.playerShip.weapon == WEAPON.DUAL_LASER) {
          this.updateScore(2);
        } else {
          this.updateScore(1);
        }

        // check if this completes the question
        if (this.checkWordsComplete()) {
          this.updateScore(5);

          if (this.flawless) {
            this.updateScore(25);

            let flawlessText = this.add.bitmapText(config.width/2, config.height * 0.75, 'kenvector', 'FLAWLESS', FONT_SIZE * 2).setTint(0xffcc00).setOrigin(0.5);
            this.tweens.add({
              targets: flawlessText,
              props: {
                scale: {from: 0, to: 1, duration: 1000, ease: 'Back.easeOut'},
                alpha: {value: 0, duration: 2000, ease: 'Linear', delay: 2000}
              },
              onComplete: function() { flawlessText.destroy();}
            });
          // create excellent tween
          } else if (this.excellent) {
            this.updateScore(10);

            let excellentText = this.add.bitmapText(config.width/2, config.height * 0.75, 'kenvector', 'EXCELLENT', FONT_SIZE * 2).setTint(0x00ccff).setOrigin(0.5);
            this.tweens.add({
              targets: excellentText,
              props: {
                scale: {from: 0, to: 1, duration: 1000, ease: 'Back.easeOut'},
                alpha: {value: 0, duration: 2000, ease: 'Linear', delay: 2000}
              },
              onComplete: function() { excellentText.destroy();}
            });
          }

          // the answer text is moved to the middle of the screen and then shrinks away to nothing.
          let tween = this.tweens.add({
              targets: this.answerText,
              props: {
                  y: {value: config.height / 2, duration: 1000, ease: 'Back.easeInOut'},
                  scale: { value: 0, duration: 1000, ease: 'Back.easeIn', delay: 3000}
              },
              //completeDelay: 2000,
              onComplete: function() {
                this.transitionNextQuestion();
              },
              callbackScope: this
          });
        }
      } else {
        // we've hit a meteor but it doesn't contain the next answer we are looking for.
        this.flawless = false;

        if (this.playerShip.weapon == WEAPON.FREEZE_GUN) {
          // freeze this meteor.
          this.freezeMeteor(gameObject);

          this.emitter_sparks_frozen.emitParticle(2, pointer.x, pointer.y);
        } else {
          // hit the meteor but don't destroy it.
          this.emitter_sparks.emitParticle(1, pointer.x, pointer.y);
        }
      }
    }
  }

  update(time, delta) {
    let mets = this.meteors.getChildren();
    for (let i=0; i<MAX_METEORS; i++) {
      this.moveMeteor(mets[i]);
    }

    this.background.tilePositionY -= 1.5;
  }
}
