const gqlUrl = "http://shop-roles.asmer.fs.a-level.com.ua/graphql";

const  yourDiv = document.getElementById("categories");

const goodsDiv = document.getElementById("goodsBox");
goodsDiv.style = "display:flex"

if(localStorage.authtoken) {
    loginFormDiv.innerHTML = ""
    let sayHi = document.createElement("h2");
    sayHi.setAttribute("style", "margin-bottom: 0px")
    sayHi.innerText = `Hi, user!`;
    loginFormDiv.appendChild(sayHi);
}


const getGQL = url => (query, variables = {}) => 
        fetch(url, {
                method: 'POST', 
                headers: {
                  'Accept': 'application/json',
                  'Content-Type': 'application/json',
                  ...(localStorage.authToken ? {Authorization: `Bearer ${localStorage.authToken}`} : {})
                },
                body: JSON.stringify({query, variables})
        }).then(res => res.json())



getGQL(gqlUrl)(`
query categories {
    CategoryFind(query:"[{}]") {
      _id name 
      goods {name, price _id, images {url}}
      image {
        _id
        createdAt
        text
        
        originalFileName
      }
    }
  }
`).then(res => categories(res, yourDiv));




function categories(data, parentEl) {
    var list = document.createElement("ul");
    parentEl.appendChild(list);
    for(let i = 0; i < data.data.CategoryFind.length; i++) {
        let oneCat = document.createElement("li");
        if(data.data.CategoryFind[i].subCategories) {
            oneCat.innerText = `${data.data.CategoryFind[i].name} >`;
        } else {
            oneCat.innerText = data.data.CategoryFind[i].name;
        }

        let thisSubcat = false;
        oneCat.onclick = () =>  getGQL(gqlUrl) (
            `query categoryFind($query: String) {
                CategoryFindOne(query: $query) {
                  name,
                  goods {
                    _id
                  },
                  subCategories {name, _id}
                }
              }
        `,{query: JSON.stringify([{_id: `${data.data.CategoryFind[i]._id}` }]) }
        ).then((res) =>  {


            if(thisSubcat == false) {


                if(res.data.CategoryFindOne.subCategories) {

                    let subArray = res.data.CategoryFindOne.subCategories;
                    oneCategory(subArray, oneCat)
                    thisSubcat = true;

                } else {

                    goodsOnPage(goodsDiv, data.data.CategoryFind[i].goods)
                }



            } else {
                let lastChild = oneCat.lastChild;
                oneCat.removeChild(lastChild);
                thisSubcat = false;
            }

        }) 
        list.appendChild(oneCat);
    }
}




function oneCategory(dataArr, parentEl) {
    
    var list = document.createElement("ul");
    parentEl.appendChild(list);
    
    for(let i = 0; i < dataArr.length; i++) {

        let oneCat = document.createElement("li");
        oneCat.innerText = dataArr[i].name;

        oneCat.onclick = function(event) {  
            event.stopPropagation();

            getGQL(gqlUrl) (
            `query goods($query: String) {
                GoodFind(query: $query)  {
                  name, price,
                  images{url}, _id
                  categories {
                    _id
                    createdAt
                    name
                  }
                }
              }`,{query: JSON.stringify([{
                  "categories._id": `${dataArr[i]._id}`
                }]) }).then(res =>(goodsOnPage(goodsDiv, res.data.GoodFind)));
        }



        list.appendChild(oneCat);
    }
}


function goodsOnPage(parentEl, goodsArr = null) {
    debugger
    parentEl.innerHTML = "";
    parentEl.style = "justify-content: spase-around;"
    if(goodsArr == null||goodsArr.length == 0) {
        parentEl.innerHTML = "К сожалению нет таких товаров. Попробуйте, пожалуйста, другую категорию";
        return
    }
    for(let key of goodsArr) {


        let icon = document.createElement("div");
        parentEl.appendChild(icon);

        let iconImg = document.createElement("img");
        iconImg.setAttribute("src", `http://shop-roles.asmer.fs.a-level.com.ua/${key.images[0].url}`);
        iconImg.style = "width: 60%; height: 60%"
        icon.appendChild(iconImg);

        let iconName = document.createElement("h5");
        iconName.innerText = key.name;
        icon.appendChild(iconName);

        let iconprice = document.createElement("span");
        iconprice.innerText = `${key.price}грн`
        icon.appendChild(iconprice);
        icon.onclick = () =>  getGQL(gqlUrl) (
            `query oneGood($query: String) {
                GoodFindOne(query: $query) {
                    _id
                    createdAt
                    name
                    description
                    price
                    images{url}
                }
              }
        `,{query: JSON.stringify([{_id: `${key._id}` }]) }
        ).then((res) => oneGoodDescription(res.data.GoodFindOne, goodsDiv));

    }
}


function oneGoodDescription(data, parentEl) {
    parentEl.innerHTML = ""
    parentEl.style = "justify-content: center;"

    var icon = document.createElement("div");
    icon.style = "display: flex; justify-content: center; flex-direction: column";

    let iconImg = document.createElement("img");
    iconImg.setAttribute("src", `http://shop-roles.asmer.fs.a-level.com.ua/${data.images[0].url}`);
    iconImg.style = "width: 100%; height: 100%";
    icon.appendChild(iconImg);

    let iconName = document.createElement("h5");
    iconName.innerText = data.name;
    icon.appendChild(iconName);

    let iconDescrip = document.createElement("p");
    iconDescrip.innerText = data.description;
    icon.appendChild(iconDescrip)

    let iconprice = document.createElement("span");
    iconprice.innerText = `${data.price}грн`
    icon.appendChild(iconprice);

    parentEl.appendChild(icon);


}


function myOrder(parentEl) {
    getGQL(gqlUrl) (
        `query yourOrders {
            OrderFind(query: "[{}]") {
              _id
              total
              orderGoods {
                count
                good {
                  name
                  price
                  images {
                    url
                  }
                }
              }
              owner {
                login
              }
            }
          }
          `
    ).then((res) => {

         parentEl.innerHTML = "";
         parentEl.style = "justify-content: spase-around; ";
        
        var array = res.data.OrderFind;
        for(let i = 0; i < array.length; i++) {
            var oneOrder = array[i].orderGoods;
            let icon = document.createElement("div");

            for(let j = 0; j < oneOrder.length; j++) {

                if(oneOrder[j].good !== null) {
                    debugger
                    icon.style = "margin: 30px; border: 2px solid black; padding:30px"
                    parentEl.appendChild(icon);



                    let goodInner = document.createElement("div");
                    goodInner.style = "width: 250px; height: 200px;"
                    icon.appendChild(goodInner);


                    let goodImg = document.createElement("img");
                    goodImg.setAttribute("src", `http://shop-roles.asmer.fs.a-level.com.ua/${oneOrder[j].good.images[0].url}`);
                    goodImg.style = "width: 70px; height: 70px;"
                    goodInner.appendChild(goodImg);

                    let goodName = document.createElement("h4");
                    goodName.innerText = oneOrder[j].good.name;
                    goodInner.appendChild(goodName);

                    let goodCount = document.createElement("span");
                    goodCount.innerText = `${oneOrder[j].count} шт    `;
                    goodInner.appendChild(goodCount)

                    let goodPrice = document.createElement("span");
                    goodPrice.innerText = `${oneOrder[j].good.price} грн`;
                    goodInner.appendChild(goodPrice);
                    console.log(oneOrder)

                }
            }

            let totalOrder = document.createElement("h3");
            totalOrder.innerText = `${array[i].total} грн`;
            icon.appendChild(totalOrder);

        }
        console.log(array);
    });

}
const orders = document.getElementById("orders");
orders.onclick = () => myOrder(goodsDiv)
