/**
 * Copyright 2018 The Pennsylvania State University
 * @license Apache-2.0, see License.md for full text.
 */
import{LitElement as e,html as t}from"../../../../lit/index.js";import{store as a}from"./haxcms-site-store.js";import{autorun as s,toJS as i}from"../../../../mobx/dist/mobx.esm.js";import"../../../../@polymer/iron-ajax/iron-ajax.js";import"../../../jwt-login/jwt-login.js";import"../../../h-a-x/h-a-x.js";import"../../../simple-modal/simple-modal.js";import"../../../simple-fields/lib/simple-fields-form.js";import"./haxcms-site-dashboard.js";import{enableServices as o}from"../../../micro-frontend-registry/lib/microServices.js";import{MicroFrontendRegistry as n}from"../../../micro-frontend-registry/micro-frontend-registry.js";import{HAXStore as l}from"../../../hax-body/lib/hax-store.js";import{normalizeEventPath as r}from"../../../utils/utils.js";class HAXCMSSiteEditor extends e{static get tag(){return"haxcms-site-editor"}constructor(){super(),this.__disposer=[],this.method="POST",this.editMode=!1,globalThis.SimpleModal.requestAvailability(),s((e=>{this.editMode=i(a.editMode),this.editMode&&i(l.activeHaxBody)&&l.activeHaxBody.importContent(i(a.activeItemContent)),this.__disposer.push(e)})),s((e=>{this.manifest=i(a.manifest),this.__disposer.push(e)})),s((e=>{this.activeItem=i(a.activeItem);const t=i(a.location.baseUrl);if(t&&this.activeItem&&this.activeItem.location){const e=t.replace("/sites","").split("/");5===e.length?l.revisionHistoryLink=`/${e[2]}/gitlist/${e[3]}/logpatch/master/${this.activeItem.location}`:4===e.length?l.revisionHistoryLink=`/${e[1]}/gitlist/${e[2]}/logpatch/master/${this.activeItem.location}`:3===e.length&&(l.revisionHistoryLink=`/gitlist/${e[1]}/logpatch/master/${this.activeItem.location}`)}this.__disposer.push(e)}))}render(){return t`
      <style>
        haxcms-site-editor {
          display: block;
        }

        haxcms-site-editor[edit-mode] #editbutton {
          width: 100%;
          z-index: 100;
          right: 0;
          bottom: 0;
          border-radius: 0;
          height: 80px;
          margin: 0;
          padding: 8px;
          background-color: lightblue !important;
        }
        h-a-x {
          margin: auto;
          display: none;
        }
        haxcms-site-editor[edit-mode] h-a-x {
          display: block;
        }
      </style>
      <iron-ajax
        reject-with-request
        .headers="${{Authorization:"Bearer ${this.jwt}"}}"
        id="nodeupdateajax"
        .url="${this.saveNodePath}"
        .method="${this.method}"
        content-type="application/json"
        handle-as="json"
        @last-response-changed="${this._handleNodeResponse}"
        @last-error-changed="${this.lastErrorChanged}"
      ></iron-ajax>
      <iron-ajax
        reject-with-request
        .headers="${{Authorization:"Bearer ${this.jwt}"}}"
        id="outlineupdateajax"
        .url="${this.saveOutlinePath}"
        .method="${this.method}"
        content-type="application/json"
        handle-as="json"
        @response="${this._handleOutlineResponse}"
        @last-error-changed="${this.lastErrorChanged}"
      ></iron-ajax>
      <iron-ajax
        reject-with-request
        .headers="${{Authorization:"Bearer ${this.jwt}"}}"
        id="manifestupdateajax"
        .url="${this.saveManifestPath}"
        .method="${this.method}"
        content-type="application/json"
        handle-as="json"
        @response="${this._handleManifestResponse}"
        @last-error-changed="${this.lastErrorChanged}"
      ></iron-ajax>
      <iron-ajax
        reject-with-request
        .headers="${{Authorization:"Bearer ${this.jwt}"}}"
        id="publishajax"
        .loading="${this.publishing}"
        @loading-changed="${this.loadingChanged}"
        .url="${this.publishSitePath}"
        .method="${this.method}"
        content-type="application/json"
        handle-as="json"
        @response="${this._handlePublishResponse}"
        @last-error-changed="${this.lastErrorChanged}"
      ></iron-ajax>
      <iron-ajax
        reject-with-request
        .headers="${{Authorization:"Bearer ${this.jwt}"}}"
        id="revertajax"
        .url="${this.revertSitePath}"
        .method="${this.method}"
        content-type="application/json"
        handle-as="json"
        @response="${this._handleRevertResponse}"
        @last-error-changed="${this.lastErrorChanged}"
      ></iron-ajax>
      <iron-ajax
        reject-with-request
        .headers="${{Authorization:"Bearer ${this.jwt}"}}"
        id="syncajax"
        .url="${this.syncSitePath}"
        .method="${this.method}"
        content-type="application/json"
        handle-as="json"
        @response="${this._handleSyncResponse}"
        @last-error-changed="${this.lastErrorChanged}"
      ></iron-ajax>
      <iron-ajax
        reject-with-request
        .headers="${{Authorization:"Bearer ${this.jwt}"}}"
        id="createajax"
        .url="${this.createNodePath}"
        .method="${this.method}"
        content-type="application/json"
        handle-as="json"
        @response="${this._handleCreateResponse}"
        @last-error-changed="${this.lastErrorChanged}"
        @last-response-changed="${this.__createNodeResponseChanged}"
      ></iron-ajax>
      <iron-ajax
        reject-with-request
        .headers="${{Authorization:"Bearer ${this.jwt}"}}"
        id="deleteajax"
        .url="${this.deleteNodePath}"
        .method="${this.method}"
        content-type="application/json"
        handle-as="json"
        @response="${this._handleDeleteResponse}"
        @last-error-changed="${this.lastErrorChanged}"
        @last-response-changed="${this.__deleteNodeResponseChanged}"
      ></iron-ajax>
      <iron-ajax
        reject-with-request
        .headers="${{Authorization:"Bearer ${this.jwt}"}}"
        id="getuserdata"
        url="${this.getUserDataPath}"
        method="${this.method}"
        content-type="application/json"
        handle-as="json"
        @response="${this._handleUserDataResponse}"
        @last-error-changed="${this.lastErrorChanged}"
      ></iron-ajax>
      <h-a-x
        id="hax"
        element-align="left"
        offset-margin="48px 0 0 0"
        hide-panel-ops="hide-panel-ops"
        hide-toolbar="hide-toolbar"
      ></h-a-x>
    `}static get properties(){return{getUserDataPath:{type:String,attribute:"get-user-data-path"},method:{type:String},jwt:{type:String},saveNodePath:{type:String,attribute:"save-node-path"},createNodePath:{type:String,attribute:"create-node-path"},deleteNodePath:{type:String,attribute:"delete-node-path"},saveManifestPath:{type:String,attribute:"save-manifest-path"},publishSitePath:{type:String,attribute:"publish-site-path"},revertSitePath:{type:String,attribute:"revert-site-path"},appendTarget:{type:Object},appElement:{type:Object},syncSitePath:{type:String,attribute:"sync-site-path"},publishing:{type:Boolean},saveOutlinePath:{type:String,attribute:"save-outline-path"},appStore:{type:Object},editMode:{type:Boolean,reflect:!0,attribute:"edit-mode"},activeItem:{type:Object},manifest:{type:Object},getSiteFieldsPath:{type:String,attribute:"save-site-fields-path"},getFormToken:{type:String,attribute:"get-form-token"}}}__deleteNodeResponseChanged(e){e.detail.value&&e.detail.value.data&&e.detail.value.data.title&&(a.toast(`Page deleted ${e.detail.value.data.title}, selecting another page`,4e3),a.playSound("coin"))}__createNodeResponseChanged(e){e.detail.value&&e.detail.value.data&&e.detail.value.data.slug&&(globalThis.history.pushState({},null,e.detail.value.data.slug),globalThis.dispatchEvent(new PopStateEvent("popstate")),a.toast(`Created ${e.detail.value.data.title}!`,3e3,{hat:"random"}),a.playSound("coin"))}_handleUserDataResponse(e){e.detail.response&&e.detail.response.data&&(a.userData=e.detail.response.data,this.dispatchEvent(new CustomEvent("haxcms-user-data-updated",{composed:!0,bubbles:!0,cancelable:!1,detail:e.detail.response.data})))}lastErrorChanged(e){if(e.detail.value){console.error(e);var t=r(e)[0];switch(parseInt(e.detail.value.status)){case 405:case 401:this.dispatchEvent(new CustomEvent("jwt-login-logout",{composed:!0,bubbles:!0,cancelable:!1,detail:{redirect:!0}}));break;case 403:this.dispatchEvent(new CustomEvent("jwt-login-refresh-token",{composed:!0,bubbles:!0,cancelable:!1,detail:{element:{obj:this,callback:"refreshRequest",params:[t]}}}));break;default:a.toast(e.detail.value.status+" "+e.detail.value.statusText,5e3,{fire:!0}),a.playSound("error")}}}refreshRequest(e,t){this.jwt=e,t.body.jwt=e,t.headers={Authorization:`Bearer ${this.jwt}`},setTimeout((()=>{t.generateRequest()}),0)}loadingChanged(e){this.loading=e.detail.value}createRenderRoot(){return this}firstUpdated(e){if(l.ready){let e={detail:!0};this._storeReadyToGo(e)}globalThis.dispatchEvent(new CustomEvent("haxcms-site-editor-loaded",{bubbles:!0,composed:!0,cancelable:!1,detail:!0}));const t=globalThis.document.createElement("link");t.rel="stylesheet",t.href=new URL("../base.css",import.meta.url).href,this.querySelector("#hax").shadowRoot.querySelector("style").parentNode.insertBefore(t,this.querySelector("#hax").shadowRoot.querySelector("style").nextSibling)}updated(e){e.forEach(((e,t)=>{"appStore"==t&&this.querySelector("#hax").setAttribute("app-store",JSON.stringify(this[t])),"publishing"==t?this._publishingChanged(this[t],e):"activeItem"==t?(this.dispatchEvent(new CustomEvent("manifest-changed",{detail:this[t]})),this._activeItemChanged(this[t],e)):"manifest"==t&&(this.dispatchEvent(new CustomEvent("manifest-changed",{detail:this[t]})),this._manifestChanged(this[t],e))}))}_tokenRefreshFailed(e){this.dispatchEvent(new CustomEvent("jwt-login-logout",{composed:!0,bubbles:!0,cancelable:!1,detail:{redirect:!0}}))}connectedCallback(){super.connectedCallback(),this.windowControllers&&this.windowControllers.abort(),this.windowControllers=new AbortController,globalThis.addEventListener("jwt-login-refresh-error",this._tokenRefreshFailed.bind(this),{signal:this.windowControllers.signal}),globalThis.addEventListener("hax-store-ready",this._storeReadyToGo.bind(this),{signal:this.windowControllers.signal}),globalThis.addEventListener("json-outline-schema-active-item-changed",this._newActiveItem.bind(this),{signal:this.windowControllers.signal}),globalThis.addEventListener("json-outline-schema-active-body-changed",this._bodyChanged.bind(this),{signal:this.windowControllers.signal}),globalThis.addEventListener("haxcms-save-outline",this.saveOutline.bind(this),{signal:this.windowControllers.signal}),globalThis.addEventListener("haxcms-save-node",this.saveNode.bind(this),{signal:this.windowControllers.signal}),globalThis.addEventListener("haxcms-save-site-data",this.saveManifest.bind(this),{signal:this.windowControllers.signal}),globalThis.addEventListener("haxcms-load-site-dashboard",this.loadSiteDashboard.bind(this),{signal:this.windowControllers.signal}),globalThis.addEventListener("haxcms-load-user-data",this.loadUserData.bind(this),{signal:this.windowControllers.signal}),globalThis.addEventListener("haxcms-create-node",this.createNode.bind(this),{signal:this.windowControllers.signal}),globalThis.addEventListener("haxcms-delete-node",this.deleteNode.bind(this),{signal:this.windowControllers.signal})}loadUserData(e){this.querySelector("#getuserdata").body={jwt:this.jwt},this.querySelector("#getuserdata").generateRequest()}loadSiteDashboard(e){globalThis.document.body.querySelector("haxcms-site-dashboard")&&(this.siteDashboard=globalThis.document.body.querySelector("haxcms-site-dashboard"),this.siteDashboard.headers={Authorization:`Bearer ${this.jwt}`},this.siteDashboard.jwt=this.jwt,this.siteDashboard.method=this.method,this.siteDashboard.body={jwt:this.jwt,token:this.getFormToken,site:{name:this.manifest.metadata.site.name}},this.siteDashboard.loadEndpoint=this.getSiteFieldsPath,setTimeout((()=>{this.siteDashboard.generateRequest()}),0))}_schemaFormValueChanged(e){}async createNode(e){if(e.detail.values){var t=e.detail.values;if(t.jwt=this.jwt,t.site={name:this.manifest.metadata.site.name},this._originalTarget=e.detail.originalTarget,t.docximport)await import("../../../file-system-broker/lib/docx-file-system-broker.js").then((async e=>{o(["haxcms"]);const s=globalThis.FileSystemBroker.requestAvailability(),i=await s.loadFile("docx"),l=new FormData;l.append("method",t.docximport);let r="course";this.manifest.metadata.build&&this.manifest.metadata.structure&&(r=this.manifest.metadata.structure),l.append("type",r),l.append("parentId",t.parent),l.append("upload",i),this.setProcessingVisual();const d=await n.call("@haxcms/docxToSite",l);a.toast("finished!",300),200==d.status&&d.data&&""!=d.data.contents&&(t.items=d.data.items,await import("../../../outline-designer/outline-designer.js").then((async e=>{const a=globalThis.document.createElement("outline-designer");a.items=d.data.items,a.eventData=t,a.storeTools=!0;const s=globalThis.document.createElement("button");s.innerText="Confirm",s.classList.add("hax-modal-btn"),s.addEventListener("click",(async e=>{const t=await a.getData();let s=0,i=0,o=0;t.items.map((e=>{e.delete?s++:e.new?o++:e.modified&&i++}));let n=`${o>0?`‣ ${o} new pages will be created\n`:""}${i>0?`‣ ${i} pages will be updated\n`:""}${s>0?`‣ ${s} pages will be deleted\n`:""}`,l=!1;if(l=""==n||globalThis.confirm(`Saving will commit the following actions:\n${n}\nAre you sure?`),l){this.querySelector("#createajax").body=t,this.setProcessingVisual(),this.querySelector("#createajax").generateRequest();const e=new CustomEvent("simple-modal-hide",{bubbles:!0,composed:!0,cancelable:!0,detail:{}});globalThis.dispatchEvent(e)}}));const i=globalThis.document.createElement("button");i.innerText="Cancel",i.classList.add("hax-modal-btn"),i.classList.add("cancel"),i.addEventListener("click",(e=>{const t=new CustomEvent("simple-modal-hide",{bubbles:!0,composed:!0,cancelable:!0,detail:{}});globalThis.dispatchEvent(t)}));const o=globalThis.document.createElement("div");o.appendChild(s),o.appendChild(i),this.dispatchEvent(new CustomEvent("simple-modal-show",{bubbles:!0,cancelable:!0,composed:!0,detail:{title:"Confirm structure",elements:{content:a,buttons:o},modal:!0,styles:{"--simple-modal-titlebar-background":"transparent","--simple-modal-titlebar-color":"black","--simple-modal-width":"90vw","--simple-modal-min-width":"300px","--simple-modal-z-index":"100000000","--simple-modal-height":"90vh","--simple-modal-min-height":"400px","--simple-modal-titlebar-height":"64px","--simple-modal-titlebar-color":"black","--simple-modal-titlebar-height":"80px","--simple-modal-titlebar-background":"orange"}}}))})))}));else{this.querySelector("#createajax").body=t,this.setProcessingVisual(),this.querySelector("#createajax").generateRequest();const e=new CustomEvent("simple-modal-hide",{bubbles:!0,composed:!0,cancelable:!0,detail:{}});globalThis.dispatchEvent(e)}}}_handleCreateResponse(e){this.dispatchEvent(new CustomEvent("haxcms-trigger-update",{bubbles:!0,composed:!0,cancelable:!1,detail:!0})),this.dispatchEvent(new CustomEvent("haxcms-create-node-success",{bubbles:!0,composed:!0,cancelable:!1,detail:{value:!0,originalTarget:this._originalTarget}}))}deleteNode(e){this.querySelector("#deleteajax").body={jwt:this.jwt,site:{name:this.manifest.metadata.site.name},node:{id:e.detail.item.id}},this.setProcessingVisual(),this.querySelector("#deleteajax").generateRequest();const t=new CustomEvent("simple-modal-hide",{bubbles:!0,composed:!0,cancelable:!0,detail:{}});globalThis.dispatchEvent(t)}_handleDeleteResponse(e){globalThis.history.replaceState({},null,a.fallbackItemSlug()),globalThis.dispatchEvent(new PopStateEvent("popstate")),setTimeout((()=>{this.dispatchEvent(new CustomEvent("haxcms-trigger-update",{bubbles:!0,composed:!0,cancelable:!1,detail:!0}))}),100)}_storeReadyToGo(e){e.detail&&(l.connectionRewrites.appendJwt="jwt")}_publishingChanged(e,t){e?a.toast("Publishing...",0,{hat:"random"}):!e&&t&&a.toast("Publishing...",2e3,{hat:"random"})}_manifestChanged(e){this.activeItem&&e.metadata&&(l.connectionRewrites.appendUploadEndPoint="siteName="+e.metadata.site.name+"&nodeId="+this.activeItem.id)}_newActiveItem(e){this.activeItem=e.detail}_activeItemChanged(e,t){e&&this.manifest&&(l.connectionRewrites.appendUploadEndPoint="siteName="+this.manifest.metadata.site.name+"&nodeId="+e.id)}_handleNodeResponse(e){e.detail.value&&e.detail.value.data&&e.detail.value.data.slug&&this.activeItem.slug!==e.detail.value.data.slug&&(globalThis.history.replaceState({},null,e.detail.value.data.slug),globalThis.dispatchEvent(new PopStateEvent("popstate"))),a.toast("Page saved!",3e3,{hat:"random"}),a.playSound("coin"),this.dispatchEvent(new CustomEvent("haxcms-trigger-update",{bubbles:!0,composed:!0,cancelable:!1,detail:!0})),this.dispatchEvent(new CustomEvent("haxcms-trigger-update-node",{bubbles:!0,composed:!0,cancelable:!1,detail:!0}));let t=a.activeId;a.activeId=null,a.activeId=t}_handleOutlineResponse(e){a.toast("Outline saved!",3e3,{hat:"random"}),a.playSound("coin"),setTimeout((()=>{this.dispatchEvent(new CustomEvent("haxcms-trigger-update",{bubbles:!0,composed:!0,cancelable:!1,detail:!0}))}),100)}_handleManifestResponse(e){a.toast("Site details saved, reloading to reflect changes!",2e3),a.playSound("coin"),this.dispatchEvent(new CustomEvent("haxcms-trigger-update",{bubbles:!0,composed:!0,cancelable:!1,detail:!0})),setTimeout((()=>{globalThis.location.reload()}),2e3)}_handleRevertResponse(e){a.toast("Last save undone",2e3),a.playSound("error"),this.dispatchEvent(new CustomEvent("haxcms-trigger-update",{bubbles:!0,composed:!0,cancelable:!1,detail:!0}))}_handleSyncResponse(e){a.toast("Site synced",2e3,{hat:"random"}),a.playSound("success"),this.dispatchEvent(new CustomEvent("haxcms-trigger-update",{bubbles:!0,composed:!0,cancelable:!1,detail:!0}))}_handlePublishResponse(e){let t=e.detail.response,a=globalThis.document.createElement("span");a.innerHTML=`\n    <a href="${t.url}" target="_blank">\n      <button raised style="color:yellow;text-transform: none;font-weight: bold;">\n      ${t.label}\n      </button>\n    </a>`;const s=new CustomEvent("haxcms-toast-show",{bubbles:!0,composed:!0,cancelable:!0,detail:{text:t.response,duration:1e4,slot:a.cloneNode(!0)}});globalThis.dispatchEvent(s)}async saveNode(e){if(this.saveNodePath){let e=await l.activeHaxBody.haxToContent();this.querySelector("#nodeupdateajax").body={jwt:this.jwt,site:{name:this.manifest.metadata.site.name},node:{id:this.activeItem.id,body:e,schema:await l.htmlToHaxElements(e)}},this.setProcessingVisual(),this.querySelector("#nodeupdateajax").generateRequest()}}saveNodeDetails(e){this.saveNodePath&&(this.querySelector("#nodeupdateajax").body={jwt:this.jwt,site:{name:this.manifest.metadata.site.name},node:{id:e.detail.id,details:e.detail}},this.setProcessingVisual(),this.querySelector("#nodeupdateajax").generateRequest())}saveOutline(e){this.saveOutlinePath&&(this.querySelector("#outlineupdateajax").body={jwt:this.jwt,site:{name:this.manifest.metadata.site.name},items:e.detail},this.setProcessingVisual(),this.querySelector("#outlineupdateajax").generateRequest())}setProcessingVisual(){let e=globalThis.document.createElement("simple-icon-lite");e.icon="hax:loading",e.style.setProperty("--simple-icon-height","40px"),e.style.setProperty("--simple-icon-width","40px"),e.style.height="150px",e.style.marginLeft="8px",a.toast("Processing",5e3,{hat:"construction",slot:e})}saveManifest(e){let t=e.detail;t.manifest.theme&&t.manifest.theme.regions&&(Object.keys(t.manifest.theme.regions).forEach(((e,a)=>{t.manifest.theme.regions[e]&&t.manifest.theme.regions[e].length>0&&(t.manifest.theme[e]=t.manifest.theme.regions[e].map((e=>e.node?e.node:null)))})),delete t.manifest.theme.regions),t.cssVariable&&(t.hexCode=globalThis.SimpleColorsSharedStyles.colors[t.cssVariable.replace("--simple-colors-default-theme-","").replace("-7","")][6]),t.jwt=this.jwt,t.site?t.site.name=this.manifest.metadata.site.name:t.site={name:this.manifest.metadata.site.name},this.saveManifestPath&&(this.querySelector("#manifestupdateajax").body=t,this.setProcessingVisual(),this.querySelector("#manifestupdateajax").generateRequest())}_bodyChanged(e){l.activeHaxBody&&l.activeHaxBody.importContent(e.detail)}publishSite(e){this.publishSitePath&&(this.querySelector("#publishajax").body={jwt:this.jwt,site:{name:this.manifest.metadata.site.name}},this.setProcessingVisual(),this.querySelector("#publishajax").generateRequest())}syncSite(e){this.syncSitePath&&(this.querySelector("#syncajax").body={jwt:this.jwt,site:{name:a.manifest.metadata.site.name}},this.setProcessingVisual(),this.querySelector("#syncajax").generateRequest())}revertCommit(e){this.revertSitePath&&(this.querySelector("#revertajax").body={jwt:this.jwt,site:{name:a.manifest.metadata.site.name}},this.setProcessingVisual(),this.querySelector("#revertajax").generateRequest())}}customElements.define(HAXCMSSiteEditor.tag,HAXCMSSiteEditor);export{HAXCMSSiteEditor};