Code viewer for World: CA2 - Heejin Yoon
// Create image based on user input text
// adapted from:
// https://rapidapi.com/dezgo/api/dezgo

 
// default body is margin 0 and padding 0 
// give it more whitespace:
// Create the CSS animation dynamically
const cssStyle = document.createElement('style');
cssStyle.innerHTML = `
  .animation {
    animation: progress-ani 13s forwards;
  }

  @keyframes progress-ani {
    0% { width: 0%; }
    100% { width: 100%; }
  }
  
  .highlighted-text {
      text-align: center;
      padding: 10px;
      background-color: yellow;
      display: inline-block;
      border-radius: 5px;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
      margin: 0 auto;
   }
  
  .container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    height: 100vh;
  }

  #body {
    margin-top: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .form-control {
      width: 100%;
      max-width: 600px;
   }
   
   .row {
        display: flex;
        justify-content: space-between;
    }

    .section {
        flex: 1; 
        margin: 0 5px; 
    }

    .form-select {
        width: 100%;
    }
    
    .card-body {
        border: 8px solid black;
    }
`;

// Append the newly created style to the <head> of the document
document.head.appendChild(cssStyle);

// Apply margin and padding to the body
document.body.style.margin = '20px';
document.body.style.padding = '20px';

 
document.write ( `
<body class="d-flex justify-content-center p-0 bg-secondary">
    <div class="container d-flex justify-content-center mt-5 p-0 mx-0" >
        <h1 class="highlighted-text"> Generate Images </h1>
        <div class="card " style="width: 100%; height: 800px;">
            <div class="card-header pt-3">
                
                <h1 class="text-center mb-3">&lt;Text to Image&gt;</h1>

                <form action="" id="GenerateForm">
                    <div class="input-group mt-0">
                        <input class="form-control" id="prompt" type="text" name="" placeholder="Write Prompt here:" autocomplete="off"  >
                        <button id="Generate">Generate</button>
                    </div>
                </form>
                <div class="row d-flex justify-content-evenly">
                    <div class="section">
                        <select id="colour" class="form-select form-select-md " style="width: 80%;" aria-label=".form-select-sm example">
                            <option selected>Colour</option>
                            <option value="Red">Red</option>
                            <option value="Vermilion">Vermilion</option>
                            <option value="Orange">Orange</option>
                            <option value="Amber">Amber</option>
                            <option value="Yellow">Yellow</option>
                            <option value="Chartreuse">Chartreuse</option>
                            <option value="Green">Green</option>
                            <option value="Teal">Teal</option>
                            <option value="Blue">Blue</option>
                            <option value="Violet">Violet</option>
                            <option value="Purple">Purple</option>
                            <option value="Magenta">Magenta</option>
                            <option value="White">White</option>
                            <option value="Gray">Gray</option>
                            <option value="Black">Black</option>
                            <option value="None">None</option>
                        </select>
                    </div>
    
                    <div class="section">
                        <select id="style" class="form-select form-select-md " style="width: 60%;" aria-label=".form-select-sm example">
                            <option selected>Art Style</option>
                            <option value="8-bit">8-bit</option>
                            <option value="16-bit">16-bit</option>
                            <option value="Afro Pop">Afro Pop</option>
                            <option value="Surrealism">Surrealism</option>
                            <option value="Tattoo">Tattoo</option>
                            <option value="Tribal Tattoo">Tribal Tattoo</option>
                            <option value="Ukiyo-e">Ukiyo-e</option>
                            <option value="Watercolor">Watercolor</option>
                            <option value="Halftone">Halftone</option>
                            <option value="Pop Art">Pop Art</option>
                            <option value="Ink Drawing">Ink Drawing</option>
                            <option value="Charcoal">Charcoal</option>
                            <option value="Film Noir">Film Noir</option>
                            <option value="Chromolithographic">Chromolithographic</option>
                            <option value="Lithograph">Lithograph</option>
                            <option value="Woodcut">Woodcut</option>
                            <option value="Illuminated Manuscript">Illuminated Manuscript</option>
                            <option value="None">None</option>
                        </select>
                    </div>
                    <div class="section">
                        <select id="method" class="form-select form-select-md " style="width: 60%;" aria-label=".form-select-sm example">
                            <option value="ddim">ddim</option>
                            <option value="dpm">dpm</option>
                            <option value="euler">euler</option>
                            <option value="euler_a">euler_a</option>
                            <option value="k_lms">k_lms</option>
                            <option value="pndm">pndm</option>
                        </select>
                    </div>
                    <div class="section">
                        <label for="weight">Weight:</label>
                        <input id="weight" type="range" min="0" max="2" value="1" step="0.01">
                        <span id="weightValue">2</span>
                    </div>
                </div>
                
                <div class="progress mt-2" style="height: 10px; width: 100%;">
                    <div id="pg" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-label="Animated striped example" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" ></div>
                </div>
            </div>
            <div id="body" class="card-body d-flex justify-content-center" style="height: 600px; overflow-y: auto">
                
                <img id="image" class="rounded mx-auto d-block" alt="">

            </div>
      
        </div>

    </div>
</body>

` );


const genBtn = document.getElementById('Generate');
var prompt = document.getElementById('prompt');
const progress = document.getElementById('pg');
const colour = document.getElementById('colour');
const style = document.getElementById('style');
const method = document.getElementById('method');
const weight = document.getElementById('weight');

const dezgoURL = 'https://dezgo.p.rapidapi.com/text2image';           // can POST to this 3rd party URL

// default API key and prompt:

var apikey = "d4ec74dfd6msh9d46cdc7cd4aa16p13f2cfjsnc1c2457842cb";
var theprompt = "hello";

genBtn.addEventListener('click', async (e) => {
    e.preventDefault();
    
    console.log(colour.value, style.value, method.value);
    
    const encodedParams = new URLSearchParams();
    encodedParams.append('prompt', `${prompt.value}, :${weight.value} with ${colour.value} color, and use this art style ${style.value}.`);
    encodedParams.append('guidance', '7');
    encodedParams.append('steps', '30');
    encodedParams.append('sampler', method.value);
    encodedParams.append('upscale', '1');
    encodedParams.append('model', 'epic_diffusion_1_1');

    const options = {
      method: 'POST',
      url: dezgoURL,
      headers: {
        'content-type': 'application/x-www-form-urlencoded',
        'X-RapidAPI-Key': apikey,
        'X-RapidAPI-Host': 'dezgo.p.rapidapi.com'
      },
      body: encodedParams
    };
    
    try {
        const response = await fetch(dezgoURL, options);
        const pngBlob = await response.blob();    

        alert('Promt : ' + prompt.value);
        console.log("Got the image as a blob:", pngBlob);
        prompt.value = '';
        document.getElementById("image").src = URL.createObjectURL(pngBlob);
        progress.classList.remove('animation');
    } catch (error) {
        console.error("Error generating image:", error);
    }
});