import{v as w}from"./validation-959284d8.js";/* empty css */const r="http://localhost:8081";function m(e,t,o,a,i){return{id:e,text:t,title:o,date:a,image:i}}async function g(){const e=await fetch(`${r}/news`);if(!e.ok)throw e.statusText;return e.json()}async function p(e){const t=await fetch(`${r}/news/${e}`);if(!t.ok)throw t.statusText;return t.json()}async function h(e,t,o,a){const i=m(0,e,t,o,a),c={method:"POST",body:JSON.stringify(i),headers:{Accept:"application/json","Content-Type":"application/json"}},s=await fetch(`${r}/news`,c);if(!s.ok)throw s.statusText;return s.json()}async function y(e,t,o,a,i){const c=m(e,t,o,a,i),s={method:"PUT",body:JSON.stringify(c),headers:{Accept:"application/json","Content-Type":"application/json"}},l=await fetch(`${r}/news/${e}`,s);if(!l.ok)throw l.statusText;return l.json()}const n={form:document.getElementById("add-news-form"),list:document.getElementById("list-news"),title:document.getElementById("title"),date:document.getElementById("date"),text:document.getElementById("text"),image:document.getElementById("image"),imagePreview:document.getElementById("image-preview")},d="https://via.placeholder.com/200";function v(e){n.list.inserAdjacentHTML(P(e)),console.info("Post was creating")}function P(e){return`
${e.title}
${e.date}
${e.text}
`}async function u(){if(console.info("Try to load data"),!n.list)return;const e=await g();n.list.innerHTML="",e.forEach(t=>{n.table.appendChild(v(t))})}async function L(e,t,o,a){console.info("Try to add item");const i=await h(e,t,o,a);console.info("Added"),console.info(i),u()}async function b(e,t,o,a){console.info("Try to update item");const i=await y(e,t,o,a);console.info("Updated"),console.info(i),u()}async function f(e){const t=new FileReader;return new Promise((o,a)=>{t.onloadend=()=>{const i=t.result;o(i)},t.onerror=()=>{a(new Error("oops, something went wrong with the file reader."))},t.readAsDataURL(e)})}async function x(){const e=n.image.files[0],t=await f(e);console.info("base64 ",t),n.imagePreview.src=t}async function T(){console.info("linesPageForm");const e=()=>location.assign("/news.html");n.image.addEventListener("change",()=>x());const o=new URLSearchParams(location.search).get("id");if(o)try{const a=await p(o);n.title.value=a.title,n.date.value=a.date,n.text.value=a.text,n.imagePreview.src=a.image?a.image:d}catch{e()}n.form.addEventListener("submit",async a=>{if(console.info("Form onSubmit"),a.preventDefault(),a.stopPropagation(),!n.form.checkValidity())return;let i="";if(n.imagePreview.src!==d){const s=await(await fetch(n.imagePreview.src)).blob();i=await f(s)}o?await b(o,n.text.value,n.title.value,n.date.value):await L(n.text.value,n.title.value,n.date.value,i),e()})}document.addEventListener("DOMContentLoaded",()=>{w(),T()});
//# sourceMappingURL=add_news-1146ed73.js.map