<div class='model-select'>
    Select Model:
      <button onclick="updateModel('sphere')"><img width="20px" height="20px" src="/icons/sphere.png" title="sphere"></button>
       <button onclick="updateModel('cube')"><img width="20px" height="20px" src="/icons/cube.png" title="cube"></button>
    <button onclick="updateModel('monkey')"><img width="20px" height="20px" src="/icons/monkey.png" title="monkey"></button>
    <button onclick="updateModel('cylinder')"><img width="20px" height="20px" src="/icons/cylinder.png" title="cylinder"></button>
    
        
</div>
<div class='target-select'>
    <button onclick="addThumb()">Save Thumbnail</button>
</div>
<div class='materialwindow3d' id="container"></div>

<div class='material-parameters'>
    <form action="/materials/edit" method="post" id="matparams" onsubmit="return">

        <input type="hidden" id="id" name="id" value="{{id}}">

        <p>
            <lable for="title" class="menutitle">Title</lable><br>
            <input type="text" id="title" name="title" value="{{title}}" required>
        </p>
        <p>
            <lable for="category" class="menutitle">Category</lable><br>
            <select name="category" id="category">
            <option value="none" {{selectCheck category 'none'}}>None</option>
            <option value="floor" {{selectCheck category 'floor'}}>Floor</option>
            <option value="wallpaper" {{selectCheck category 'wallpaper'}}>Wallpaper</option>
            </select>
        </p>
         <div>
            <lable for="type" class="menutitle">Type</lable><br>
            <select name="type" id="type" onchange="checkType(this.value)">
            <option value="MeshStandardMaterial" {{selectCheck type 'MeshStandardMaterial'}}>MeshStandardMaterial</option>
            <option value="MeshPhysicalMaterial" {{selectCheck type 'MeshPhysicalMaterial'}}>MeshPhysicalMaterial</option>
            </select>
            <p>
            See threejs documentation for explanation of values:<br>
            <a href="https://threejs.org/docs/index.html?q=materi#api/en/materials/MeshStandardMaterial">MeshStandardMaterial</a><br>
            <a href="https://threejs.org/docs/index.html?q=materi#api/en/materials/MeshPhysicalMaterial">MeshPhysicalMaterial</a>
            </p>
         </div>
        <p>
            <lable for="extension" class="menutitle">Extension (added to SKU by default)</lable><br>
            <input type="text" id="extension" name="extension" value="{{extension}}" >
        </p>
        <p>
            <lable for="color_hex" class="menutitle">Color</lable><br>
            <input type="color" id="color_hex" name="color_hex" value="{{color_hex}}"
                oninput="updateField(this.id,this.value)">
        </p>
        <div>
            <lable for="diffuse_map" class="menutitle">Diffuse Map</lable><br>
            <div class="map-preview" ><img width="100%" height="100%"
                    id="diffuse_map_prev" onclick="imageChoose('diffuse_map')" /><div class="delete-bt" id="diffuse_map_remove" onclick="updateField('diffuse_map',null)"><span class="material-icons" style="margin: -2px;">
                        highlight_off
                    </span></div></div><input class="image-input" type="text" id="diffuse_map"
                name="diffuse_map" value="{{diffuse_map}}">
        </div>
        <div>
            <lable for="opacity_value" class="menutitle">Opacity</lable><br>
            <input type="range" id="opacity_value" name="opacity_value" min="0" max="1" step="0.01"
                value="{{opacity_value}}" oninput="updateField(this.id,this.value)"><span id="opacity_value_display">{{opacity_value}}</span>
        </div>
        <p>
            <lable for="emissive_hex" class="menutitle">Emissive Color</lable><br>
            <input type="color" id="emissive_hex" name="emissive_hex" value="{{emissive_hex}}" oninput="updateField(this.id,this.value)">
        </p>
        <p>
            <lable for="roughness_value" class="menutitle">Roughness</lable><br>
            <input type="range" id="roughness_value" name="roughness_value" min="0" max="1" step="0.01"
                value="{{roughness_value}}" oninput="updateField(this.id,this.value)"><span id="roughness_value_display">{{roughness_value}}</span>     
        </p>
        <p>
             <lable for="roughness_map" class="menutitle">Roughness Map</lable><br>
            <div class="map-preview" ><img width="100%" height="100%"
                    id="roughness_map_prev" onclick="imageChoose('roughness_map')" /><div class="delete-bt" id="roughness_map_remove" onclick="updateField('roughness_map',null)"><span class="material-icons" style="margin: -2px;">
                        highlight_off
                    </span></div></div><input class="image-input" type="text" id="roughness_map"
                name="roughness_map" value="{{roughness_map}}">
        </p>
        <p>
            <lable for="metalness_value" class="menutitle">Metalness</lable><br>
            <input type="range" id="metalness_value" name="metalness_value" min="0" max="1" step="0.01"
                value="{{metalness_value}}" oninput="updateField(this.id,this.value)"><span id="metalness_value_display">{{metalness_value}}</span>
        </p>
        
        <div>
            <lable for="normal_map" class="menutitle">Normal Map</lable><br>
            <div class="map-preview" ><img width="100%" height="100%"
                    id="normal_map_prev" onclick="imageChoose('normal_map')" /><div class="delete-bt" id="normal_map_remove" onclick="updateField('normal_map',null)"><span class="material-icons" style="margin: -2px;">
                        highlight_off
                    </span></div></div> <input class="image-input" type="text" id="normal_map"
                name="normal_map" value="{{normal_map}}">
        </div>
        <p>
            <lable for="normal_value" class="menutitle">Normal Amount</lable><br>
            <input type="range" id="normal_value" name="normal_value" min="0" max="1" step="0.01"
                value="{{normal_value}}" oninput="updateField(this.id,this.value)"><span id="normal_value_display">{{normal_value}}</span>
        </p>
        <div>
            <lable for="bump_map" class="menutitle">Bump Map</lable><br>
            <p>Note that if a normal map is defined, the bump map will be ignored</p>
            <div class="map-preview" ><img onclick="imageChoose('bump_map')"  width="100%" height="100%"
                    id="bump_map_prev" />
                <div class="delete-bt" id="bump_map_remove" onclick="updateField('bump_map',null)"><span class="material-icons" style="margin: -2px;">
                        highlight_off
                    </span></div>
            </div><input class="image-input" type="text" id="bump_map" name="bump_map" value="{{bump_map}}"
                oninput="updateField(this.id,this.value)">
        </div>
        <div>

            <lable for="bump_value" class="menutitle">Bump Amount</lable><br>
            <input type="range" id="bump_value" name="bump_value" min="0" max="0.1" step="0.0001" value="{{bump_value}}"
                oninput="updateField(this.id,this.value)"><span id="bump_value_display">{{bump_value}}</span>
        </div>
        <div id="physical">
            <h3>Extra Physical Material Properties</h3>
       <div>
            <lable for="transmisson" class="menutitle">Transmission</lable><br>
            <input type="range" id="transmission" name="transmission" min="0" max="1" step="0.0001" value="{{transmission}}"
                oninput="updateField(this.id,this.value)">
                <span id="transmission_display">{{transmission}}</span>
        </div>
          <div>
            <lable for="ior" class="menutitle">Refraction</lable><br>
            <input type="range" id="ior" name="ior" min="1" max="2" step="0.0001" value="{{ior}}"
                oninput="updateField(this.id,this.value)">
                <span id="ior_display">{{ior}}</span>
        </div>
        <div>
            <lable for="reflectivity" class="menutitle">Reflectivity</lable><br>
            <input type="range" id="reflectivity" name="reflectivity" min="0" max="1" step="0.0001" value="{{reflectivity}}"
                oninput="updateField(this.id,this.value)">
                <span id="reflectivity_display">{{reflectivity}}</span>
        </div>
          <div>
            <lable for="thickness" class="menutitle">Thickness</lable><br>
            <input type="range" id="thickness" name="thickness" min="0" max="5" step="0.0001" value="{{thickness}}"
                oninput="updateField(this.id,this.value)">
                <span id="thickness_display">{{thickness}}</span>
        </div>
          <div>
            <lable for="clearcoat" class="menutitle">clearcoat</lable><br>
            <input type="range" id="clearcoat" name="clearcoat" min="0" max="1" step="0.0001" value="{{clearcoat}}"
                oninput="updateField(this.id,this.value)">
                <span id="clearcoat_display">{{clearcoat}}</span>
        </div>
        <div>
            <lable for="clearcoat_roughness" class="menutitle">Clearcoat Roughness</lable><br>
            <input type="range" id="clearcoat_roughness" name="clearcoat_roughness" min="0" max="1" step="0.0001" value="{{clearcoat_roughness}}"
                oninput="updateField(this.id,this.value)">
                <span id="clearcoat_roughness_display">{{clearcoat_roughness}}</span>
        </div>
        </div>
        
        <div style="height: 50px;">
            <br>
               <a href="/translations/edit/materials/{{id}}/{{title}}">Edit Translations</a>
        </div>

        <div class="submit-bt">
            <button type="submit" name="submit" id="submit">
                Update
            </button>
        </div>
        <div style="height: 250px">

        </div>

    </form>
</div>
<div class="bottomButs" id='bb' style="position: fixed;bottom: 10px; right: 10px;">
    <form id='material' action="/materials/delete/" method="POST"
        onsubmit="return confirm('Are you sure you want to permanently delete this material?')">
        <input type="hidden" id="id" name="id" value="{{id}}">
        <input type="hidden" id="texture" name="texture" value="{{texture}}">
        <button class="warn" type="submit">DELETE</button>
    </form>
    <!--<button class="warn" onclick="deletemodel()">Delete</button>-->
    <button onclick="window.location.href='/materials'">Cancel</button>
</div>
<div id="images" class="image-chooser"></div>
<script>
    function startup() {
        
       // loadModelList();
         let type = document.getElementById('type').value;
        checkType(type);
        loadModel('sphere.glb', updateMaterial);
    }
    function updateModel(model){
        loadModel(model +'.glb');
      
    }
    function checkType(value){
        console.log("checking type",value);
        switch(value){
            case 'MeshPhysicalMaterial':
                document.getElementById('physical').style.display = "block";
                let extras = {};
                extras.transmission = document.getElementById('transmission').value;
                extras.ior = document.getElementById('ior').value;
                extras.reflectivity = document.getElementById('reflectivity').value;
                extras.thickness = document.getElementById('thickness').value;
                extras.clearcoat = document.getElementById('clearcoat').value;
                extras.clearcoatRoughness = document.getElementById('clearcoat_roughness').value;
                changeMaterialType('MeshPhysicalMaterial', extras);
            break;
            case 'MeshStandardMaterial':
                document.getElementById('physical').style.display = "none";
                changeMaterialType('MeshStandardMaterial');
            break;
            default:
                document.getElementById('physical').style.display = "none";
                changeMaterialType('MeshStandardMaterial');
            break;
        }
    }
    function changeMat(type){
        
    }
    function updateMaterial() {
        console.log("updating material");
        applyMaterialProperty('color_hex', '{{color_hex}}');
        applyMaterialProperty('emissive_hex', '{{emissive_hex}}');
        applyMaterialProperty('opacity_value', '{{opacity_value}}');
        applyMaterialProperty('roughness_value', '{{roughness_value}}');
        applyMaterialProperty('metalness_value', '{{metalness_value}}');
        applyMaterialProperty('normal_value', '{{normal_value}}');
        applyMaterialProperty('bump_value', '{{bump_value}}');
        
        var diffuse = '{{diffuse_map}}';
        if (diffuse.length > 3) {
            applyMaterialProperty('diffuse_map', diffuse);
            loadThumb('diffuse_map', diffuse);
        }
        var normal = '{{normal_map}}';
        if (normal.length > 3) {
            applyMaterialProperty('normal_map', normal);
            loadThumb('normal_map', normal);
        }
        var bump = '{{bump_map}}';
        if (bump.length > 3) {
            applyMaterialProperty('bump_map', bump);
            loadThumb('bump_map', bump);
        }
         var roughness = '{{roughness_map}}';
        if (roughness.length > 3) {
            applyMaterialProperty('roughness_map', roughness);
            loadThumb('roughness_map', roughness);
        }

        if(document.getElementById('type').value == "MeshPhysicalMaterial"){
            applyMaterialProperty('transmission', '{{transmission}}');
            applyMaterialProperty('ior', '{{ior}}');
            applyMaterialProperty('reflectivity', '{{reflectivity}}');
            applyMaterialProperty('thickness', '{{thickness}}');
            applyMaterialProperty('clearcoat', '{{clearcoat}}');
            applyMaterialProperty('clearcoat_roughness', '{{clearcoat_roughness}}');
        }
        render();
    }
    function loadThumb(field, value) {
        let targ = document.getElementById(field + '_prev');
        let removeButton = document.getElementById(field + '_remove');
        console.log(value);
        if(value == null || value == 'null' || value == ''){
            $(targ).attr('src', null);
            $(removeButton).css('display','none');
        }else{
            targ.src = '/thumbs/textures/' + value; 
             $(removeButton).css('display','block');
        }
    }
    function registerTargets(targets) {
        console.log(targets);
    }
    function imageChoose(field) {
        console.log("changing", field);
        fetch('/textures/all')
            .then(response => response.json())
            .then(data => {
                let htmlstr = '';
                var i;
                let thumb;
                console.log(data);
                for (i = 0; i < data.length; i++) {
                    thumb = data[i].texture;
                    htmlstr += '<div class="thumb-img" onclick="updateField(\'' + field + '\',\'' + thumb + '\')"><img title="'+data[i].title+'" src="/thumbs/textures/' + thumb + '"><div style="width:80px;overflow:hidden;font-size:10px">'+data[i].title+'</div></div>';
                }
                htmlstr += '<div style="display: grid;position: relative;width: 99%;"><button onclick="cancelImagePicker()">CANCEL</button></div>'
                var imgBrowse = document.getElementById('images');
                imgBrowse.innerHTML = htmlstr;

            });

    }
    function cancelImagePicker(){
        var imgBrowse = document.getElementById('images');
            imgBrowse.innerHTML = '';
    }
    function updateField(field, value) {
        console.log("value", field, value)
        let f = document.getElementById(field);
        f.value = value;

        let disp = document.getElementById(field + "_display");
        if(disp)  disp.innerHTML = value;
      
        //for maps...
        if (field.includes('_map')) {
            loadThumb(field, value);
            var imgBrowse = document.getElementById('images');
            imgBrowse.innerHTML = '';
        }
        applyMaterialProperty(field, value);

    }
    function updateColor(target) {
        console.log(target.value);
        applyMaterialProperty('color', target.value);

    }
    function addThumb() {

        var t = grabScreenshot();
        var _id = '{{id}}';
        console.log("save thumb");
        $.ajax({
            type: "POST",
            url: "/materials/thumb",
            data: {
                imgBase64: t,
                id: _id
            }
        }).done(function (o) {
            console.log('saved');
            return true;
        });

    }
    function loadModelList() {
        fetch('/models/all')
            .then(response => response.json())
            .then(data => {
                console.log(data);
                var i;
                for (i = 0; i < data.length; i++) {
                    data[i].name = data[i].title;
                    data[i].id = data[i].model;
                }

                $('.allmodels').dropdown({
                    data: data,
                    limitCount: 40,
                    input: '<input type="text" maxLength="20" placeholder="Search">',
                    choice: function () {
                        loadModel(document.getElementById('models').value, updateMaterial);
                    }
                });
            });
    }
</script>

{{>preview3d}}