<template>
  <div id="generatorContainer" ref="generatorContainer">
    <div class="imgContainer" :id="'div'+item.id" :class="{highlightItem: item.isHighlight===1, highlightMax: item.isHighlight===2, graffStyle: item.isHighlight===3}" v-for="item in partOneItem" :key="item.id" :style="{
                                                                                                left: item.x + 'px',
                                                                                                top: item.y + 'px'
                                                                                              }">
          <img :src="item.src" class="imgStyle" :class="{highlightItem: item.isHighlight===1, highlightMax: item.isHighlight===2, graffStyle: item.isHighlight===3}" :id="'image'+item.id">

    </div>
    <div class="imgContainer" :id="'div'+item.id" :class="{highlightItem: item.isHighlight===1, highlightMax: item.isHighlight===2, graffStyle: item.isHighlight===3}" v-for="item in partTwoItem" :key="item.id" :style="{
                                                                                                left: item.x + 'px',
                                                                                                top: item.y + 'px'
                                                                                              }">
          <img :src="item.src" class="imgStyle" :class="{highlightItem: item.isHighlight===1, highlightMax: item.isHighlight===2, graffStyle: item.isHighlight===3}" :id="'image'+item.id">

    </div>
    <div class="imgContainer" :id="'div'+item.id" :class="{highlightItem: item.isHighlight===1, highlightMax: item.isHighlight===2, graffStyle: item.isHighlight===3}" v-for="item in partThreeItem" :key="item.id" :style="{
                                                                                                left: item.x + 'px',
                                                                                                top: item.y + 'px'
                                                                                              }">
          <img :src="item.src" class="imgStyle" :class="{highlightItem: item.isHighlight===1, highlightMax: item.isHighlight===2, graffStyle: item.isHighlight===3}" :id="'image'+item.id">

    </div>
  </div>
</template>

<style scoped>
  /*=====================Generated Content CSS*/
  #generatorContainer{
    pointer-events: none;
    position:absolute;
    inset:0;
    z-index: 3;
    background-color: transparent;
    box-sizing: border-box;
  }

  /*====================Gestion des images*/
  .imgContainer{
    width:150px;
    height:150px;
    position:absolute;
    z-index:0;
    align-items:center;
    display:flex;
    background-color:transparent;
  }

  .imgStyle{
    height:auto;
    z-index:1;
    border-style: solid;
    border-width: thin;
    border-color: var(--light-color);

  }
  .imgStyle.highlightItem{
    border-color: transparent;
  }
  .imgStyle.highlightMax{
    border-color: transparent;
  }
  .imgStyle.graffStyle{
    border-color: transparent;
  }
  /*Highlights z-index*/
  div.highlightItem{
    z-index: 3;
  }
  div.highlightMax{
    z-index: 4;
  }
  div.graffStyle{
    z-index: 5;
    position:absolute;
    margin-left: 100px;
  }

  /*===============format large*/
  @media (min-width:800px){
      .imgStyle{
        width:100px;
      }

      /*Highlights size*/
          .imgStyle.highlightItem{
            width:250px;
            height:auto;
            z-index:3;
          }
          .imgStyle.highlightMax{
            width:444px;
            height:auto;
            z-index:4;
          }
          .imgStyle.graffStyle{
            width:100px;
            height:auto;
            z-index: 5;
          }

      }

  /*=============== (prononcé avec l'intonation de grouz) format moyen mes couilles là*/
  @media (max-width:800px){
        .imgStyle{
          width:77px;
        }

        /*Highlights size*/
            .imgStyle.highlightItem{
              width:133px;
              height:auto;
              z-index:3;
            }
            .imgStyle.highlightMax{
              width:250px;
              height:auto;
              z-index:4;
            }
            .imgStyle.graffStyle{
              width:77px;
              height:auto;
              z-index: 5;
            }
      }

  /*===============format tres haut*/
  @media (max-width:500px){
        .imgStyle{
          width:50px;
        }

        /*Highlights size*/
            .imgStyle.highlightItem{
              width:100px;
              height:auto;
              z-index:3;
            }
            .imgStyle.highlightMax{
              width:200px;
              height:auto;
              z-index:4;
            }
            .imgStyle.graffStyle{
              width:50px;
              height:auto;
              z-index: 5;

            }
    }

</style>

<script>
  import { toRaw } from 'vue'

  const impGraff = import.meta.glob('../assets/collectionsData/graffBackground/*.png',{eager:true,import:'default'});
  const graffData = Object.values(impGraff);

  const collection01 = import.meta.glob('../assets/collectionsData/noirRose/*.png',{eager:true,import:'default'});
  const imgList01 = Object.values(collection01);
  const allCollections = [
    {
    imgData: imgList01,
    associatedTheme: "green",
    associatedHighlight: [['img-2',1],['img-7',1],['img-11',2]]
    }
  ];

  export default {
    name:'GeneratedContent',
    data(){
      return{
        collectionMaxCount: allCollections.length,
        collectionCount:0,
        allCollections,
        items: null,
        randomItems:null,
        graffs: graffData.map((src, index) => ({
          id: "graff-" + index,
          src: src,
          x: 0,
          y: 0,
          isHighlight: 3
        })),
        maxItemCount:0,
        marjTop:0,
        marjBot:0,
        marjSide:0,
        partOne:0,
        partTwo:0,
        partThree:0,
        partOneItem:[],
        partTwoItem:[],
        partThreeItem:[],
        containerWidth:0,
        containerHeight:0
      }
    },
    computed:{
      currentCollection(){
        return this.allCollections[this.collectionCount]
      },
      currentTheme(){
        return this.currentCollection.associatedTheme
      },
      currentHighlight(){
        return this.currentCollection.associatedHighlight
      },
      currentImgData(){
        return this.currentCollection.imgData
      }
    },
    methods:{
      getRandomInt(min,max){
        min=Math.ceil(min)
        max=Math.floor(max)
        return Math.floor(Math.random()*(max-min+1))+min
      },
      selectCollection(){
        let indexDir=this.getRandomInt(0,1);
        this.collectionCount+=1-2*indexDir;
        if(this.collectionCount<0){
          this.collectionCount=this.collectionMaxCount-1;
        };
        if(this.collectionCount>=this.collectionMaxCount){
          this.collectionCount=0;
        };
      },
      organizeContent(){
        document.documentElement.setAttribute("data-theme", this.currentTheme);
        this.items = this.currentImgData.map((src, index) => ({
          id: "img-" + index,
          src: src,
          x: 0,
          y: 0,
          isHighlight: 0
        }));
      },
      selectHighlight(){
        this.currentHighlight.forEach(([id, level]) => {
          const item = this.items.find(item => item.id === id);
          if (item) item.isHighlight = level;
        });
      },
      selectRandomGraffs(){
        const graffCount = this.graffs.length-1;
        let a = this.getRandomInt(0,graffCount);
        let b = 0;
        let c = 0;
        do{
          b = this.getRandomInt(0,graffCount);
        } while (a == b);

        do{
          c = this.getRandomInt(0,graffCount);
        } while (a == c || c == b);
        console.log(a,b,c);
          this.randomItems.push({...this.graffs[a]},{...this.graffs[b]},{...this.graffs[c]});
      },
      divideItem(){
        const half = Math.floor(this.maxItemCount/2)+1;
        this.partOne = this.getRandomInt(1,half);
        this.partTwo = this.getRandomInt(1,half);
        this.partThree = this.maxItemCount-this.partTwo-this.partOne;
        console.log(this.partOne,this.partTwo,this.partThree);
      },
      createEmptyArray(){
        this.partOneItem = this.randomItems.slice(0, this.partOne);
        this.partTwoItem = this.randomItems.slice(this.partOne, this.partOne + this.partTwo);
        this.partThreeItem = this.randomItems.slice(this.partOne + this.partTwo);
        console.log(this.partOneItem,this.partTwoItem,this.partThreeItem);
      },
      genCoord(chain){
        const maxX = this.containerWidth;
        const maxY = this.containerHeight;

        // position initiale aléatoire
        let x = this.getRandomInt(0, maxX-this.marjSide);
        let y = this.getRandomInt(0, this.marjSide);

        // vecteur direction initial aléatoire mais biais vers le bas
        let dirX = (Math.random() - 0.5) * 5;
        let dirY = Math.random() * 2 + 0.7;

        for (let i = 0; i < chain.length; i++){

          // assigner position
          chain[i].x = x;
          chain[i].y = y;

          // distance contrôlée
          const distance = this.getRandomInt(100, this.marjSide);

          // perturbation continue
          dirX += (Math.random() - 0.5) * 1.2;
          dirY += (Math.random() - 0.5) * 0.5;

          // perturbation brutale occasionnelle
          if (Math.random() < 0.5){
            dirX += (Math.random() - 0.5) * 3;
            dirY += (Math.random() - 0.5) * 1;
          }

          // biais vers le bas
          dirY += .2;

          // normaliser
          const length = Math.sqrt(dirX*dirX + dirY*dirY);
          dirX /= length;
          dirY /= length;

          // déplacement
          x += dirX * distance;
          y += dirY * distance;

          // rebond horizontal
          if (x <= 0){
            x = 0;
            dirX *= -1;
          }

          if (x >= maxX-this.marjSide){
            x = maxX-this.marjSide;
            dirX *= -1;
          }

          //limite en bas
          if (y>=maxY-this.marjBot){
            y = maxY-this.marjBot;
            dirY *= -1;
          }

          //limite haut
          if (y<=this.marjTop){
            y = this.marjTop;
            dirY *= -1;
          }

        }

      },
      calcMarj(){
        const maxX = window.innerWidth;
        if (maxX>=800){
          this.marjBot = 300;
          this.marjTop = 300;
          this.marjSide = 300;
          console.log(this.marjTop,this.marjBot,this.marjSide);
          return
        }
        if (maxX<=500){
          this.marjBot = 150;
          this.marjTop = 80;
          this.marjSide = 150;
        }else{
          this.marjBot = 300;
          this.marjTop = 80;
          this.marjSide = 250;
        }
        console.log(this.marjTop,this.marjBot,this.marjSide);
      },
      generateContent(){
        this.selectCollection();
        this.organizeContent();
        this.selectHighlight();
        this.randomItems = structuredClone(toRaw(this.items)).sort(() => Math.random()-0.5);
        this.selectRandomGraffs();
        console.log(this.randomItems);
        this.maxItemCount = this.randomItems.length;
        this.divideItem();
        this.createEmptyArray();
        this.calcMarj();
        this.genCoord(this.partOneItem);
        this.genCoord(this.partTwoItem);
        this.genCoord(this.partThreeItem);
        console.log('Content has been generated!');
      }
    },
    mounted(){
        const el = this.$refs.generatorContainer;
        if(!el){
          console.error("container not found");
          return
        };

        const observer = new ResizeObserver(entries=>{
          const rect = entries[0].contentRect;
          this.containerWidth = rect.width;
          this.containerHeight = rect.height;
          console.log(rect.width, rect.height);
          this.generateContent();
        });
        observer.observe(el);
      console.log("Content generator is loaded!");
    }
  }
</script>
