<script>
  // import P5 from 'p5-svelte';

  let images = {};
  export let deck = [];

  class Card {
    value;
    suit;
    type;
    image;

    constructor(value, suit, type, image)
    {
      this.value = value;
      this.suit = suit;
      this.type = type;
      this.image = image;
    }

    getValue() {
      return this.value;
    }

    getSuit() {
      return this.suit;
    }

    getType() {
      return this.type;
    }

    getImage()
    {
      return this.image;
    }
  }

  export function loadDeckImages(p5)
  {
      const loop = ["Back", "Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"];
      const suits = ["Hearts", "Diamonds", "Spades", "Clubs"];
      for(const suit of suits)
      {
          for(const num of loop)
          {
              const pathString = ("./src/assets/" + suit) + num + ".png";
              const nameString = ("" + suit) + num;
              images[nameString] = p5.loadImage(pathString);
          }
      }

      images["Back"] = p5.loadImage("./src/assets/Back.png");
  }

  export function createDeck()
  {
      let indexSuit = "Hearts"
      let indexVal = 1;
      function switchSuit()
      {
          switch(indexSuit) {
              case "Hearts":
                  indexSuit = "Diamonds";
                  break;
              case "Diamonds":
                  indexSuit = "Clubs";
                  break;
              case "Clubs":
                  indexSuit = "Spades";
                  break;
              case "Spades":
                  indexSuit = "Hearts";
                  break;
          }
      }

      const placeholder = new Array(52).fill(0);
      deck = placeholder.map((obj) => {
          const val = indexVal;
          const suit = indexSuit;

          let nameString = suit;

          let type;
          if(indexVal == 1){
            type = "Ace";
            nameString += type;
          }
          else if(indexVal <= 10)
          {
            type = "Number";
            nameString += indexVal
          }
          else {
            type = "Face";
            switch(indexVal) {
              default:
                nameString += "Back";
                break;
              case 11:
                nameString += "Jack";
                break;
              case 12:
                nameString += "Queen";
                break;
              case 13:
                nameString += "King";
                break;
            }
          }

          indexVal += 1;
          if(indexVal > 13){ 
              indexVal = 1;
              switchSuit();
          }

          return new Card(val, suit, type, images[nameString])
      });

      return deck;
  }

  export function shuffleDeck()
  {
    deck.sort((a, b) => Math.random() - 0.5);
  }

  export function drawCard()
  {
    return deck.pop();
  }

  export function getRemaining()
  {
    return deck.length;
  }

  export function getBackCardImage()
  {
    return images["Back"];
  }
</script>


