import { LitElement, html } from 'lit-element';
import { HostVars } from './support/crest-styles.js';
import { PaperInputStyle } from './support/paper-input-utils.js';
import { persistence } from './support/persistence.js';

// import '@polymer/paper-input/paper-textarea.js';
import '@polymer/paper-icon-button/paper-icon-button.js';
import '@polymer/iron-icons/iron-icons.js';
import '@polymer/iron-icons/image-icons.js';
import '@polymer/iron-pages/iron-pages.js';
import '@polymer/paper-tabs/paper-tab.js';
import '@polymer/paper-tabs/paper-tabs.js';

import './admin-bundle.js';
import './admin-settings.js';


export const adminTabs = {
    settings: 0,
    urls: 1,
    headers: 2,
    bundles: 3
};

/**
 * Lots to do here to make it better, for now just quickly hack together 
 * something to update urls and headers.
 */
class CRestAdmin extends LitElement {
    static get properties() {
        return {
            // selected: { type: Number}
        };
    }

    constructor() {
        super();
    }

    render() {
        return html `
            ${HostVars}
            ${PaperInputStyle}
            <style>
                .overlay {
                    height: 100%;
                    width: 100%;
                    display: block;
                    position: fixed;
                    z-index: 2000;
                    top: 0;
                    left: 0;
                    /* background-color: rgb(0,0,0); */
                    /* background-color: rgba(0,0,0, 0.9); */
                    /* this is rgb version of  efefef used as page background*/
                    background-color: #efefef;
                    overflow: auto;
                    overflow-y: scroll;/*force scroll bar*/
                }
                .fade-visible {
                    visibility: visible;
                    opacity: 1;
                    /* transition: opacity .1s linear; */
                }
                
                .fade-hidden {
                    visibility: hidden;
                    /* opacity: 0;
                    transition: visibility 0s .1s, opacity .1s linear; */
                }

                .closebtn {
                    position: absolute;
                    top: 14px;
                    right: 14px;
                    /* background: #ff4d4d; */
                    background: #fff;
                    border-radius: 50%;
                    padding: 2px;
                    width: 21px;
                    height: 21px;
                    box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14),
                                0 1px 5px 0 rgba(0, 0, 0, 0.12),
                                0 3px 1px -2px rgba(0, 0, 0, 0.2);
                }
                paper-icon-button:hover {
                    color: black;
                }
                div#content {
                    box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14),
                                0 1px 5px 0 rgba(0, 0, 0, 0.12),
                                0 3px 1px -2px rgba(0, 0, 0, 0.2);
                    padding: 16px;
                    margin: 24px;
                    border-radius: 5px;
                    background-color: var(--content-box-bg-color);
                }
                textarea {
                    /* height: 100%; */
                    width: 99%;
                    outline: none;
                    border: 1px solid #d4d4d4;
                }
                paper-button {
                    margin: 0px;
                }
                
                paper-tabs {
                    /* background-color: var(--crest-dark-blue);
                    color: #fff;
                    --paper-tabs-selection-bar-color: #f7e238; */

                    background-color: #fff;
                    /* color: #fff; */
                    --paper-tabs-selection-bar-color: var(--crest-dark-blue);
                    --paper-tab-ink: var(--crest-dark-blue);

                }

            </style>
            <div id="adminDiv" class="overlay fade-hidden">
                <paper-icon-button id='close' @click="${this._close}" class="closebtn" icon="close">Close</paper-icon-button>
                <div id="content">
                    <paper-tabs fit-container>
                        <paper-tab>Settings</paper-tab>
                        <paper-tab>URL History</paper-tab>
                        <paper-tab>Header History</paper-tab>
                        <paper-tab>Bundles</paper-tab>
                    </paper-tabs>
                    <iron-pages>
                        <crest-settings-admin></crest-settings-admin>
                        <div>
                            <br/>
                            <textarea id="urls" rows="25" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"></textarea>
                            <paper-button id="urls" @click="${() => this._saveUrls()}" raised noink>Save</paper-button>
                        </div>
                        <div>
                            <br/>
                            <textarea id="headers" rows="25" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"></textarea>
                            <paper-button id="headers" @click="${() => this._saveHeaders()}" raised noink>Save</paper-button>
                        </div>
                        
                        <crest-bundle-admin .admin="${this}"></crest-bundle-admin>
                        
                    </iron-pages>
               </div>
            </div>
        `;
    }

    /**
     * Good read here on dealing with an overlay & scrolling with overlay vs main document scrolling: 
     *      https://stackoverflow.com/questions/9280258/prevent-body-scrolling-but-allow-overlay-scrolling 
     */
    firstUpdated() {
        this.adminDiv = this.shadowRoot.querySelector('div#adminDiv');
        this.settings = this.shadowRoot.querySelector('crest-settings-admin');
        this.bundleAdmin = this.shadowRoot.querySelector('crest-bundle-admin');
        this.buttonUrls = this.shadowRoot.querySelector('paper-button#urls');
        this.buttonUrls.disabled = true;
        this.textAreaUrls = this.shadowRoot.querySelector('textarea#urls');
        this.textAreaUrls.addEventListener('input', () => {this.buttonUrls.disabled = false;});

        this.buttonHeaders = this.shadowRoot.querySelector('paper-button#headers');
        this.buttonHeaders.disabled = true;
        this.textAreaHeaders = this.shadowRoot.querySelector('textarea#headers');
        this.textAreaHeaders.addEventListener('input', () => {this.buttonHeaders.disabled = false;});



        this.tabs = this.shadowRoot.querySelector('paper-tabs');
        this.pages = this.shadowRoot.querySelector('iron-pages');
        
        this.tabs.selected = 0;
        this.pages.selected = 0;

        this.tabs.addEventListener('selected-changed', (e) => {
            this.pages.selected = this.tabs.selected;
            //case where == is handy since this.tabs.selected can be a string or a number
            if(this.tabs.selected == adminTabs.bundles) {
                console.log('selected = admin', e);
                this.bundleAdmin._onTabSelect();
            }
        });
    }

    /**
     * used by app to know if it should close the admin
     * during bundle load event.
     */
    _isVisible() {
        return this.adminDiv.classList.contains('fade-visible');
    }
    /**
     * Supports save button for a response.
     * 
     * @param {*} completionState 
     */
    _showBundleEditor(completionState, isToken) {
        let req = completionState.req;

        if(isToken) {

            let oauthBundleAdmin = this.settings.shadowRoot.querySelector('crest-oauth-admin');

            console.log(oauthBundleAdmin);
            console.log(oauthBundleAdmin);

            oauthBundleAdmin._edit({
                name: '',
                method: req.method,
                url: req.url,
                headers: req.uiHeaderLines,
                body: (req.body) ? req.body : '',
                dateTouched: new Date().getTime(),
                isOAuth: true,
                isNewBundle: true
            });

        } else {
            console.log("showing bundle editor");
            this.bundleAdmin._lazyLoadEditor();
        
            this.bundleAdmin._edit({
                name: '',
                method: req.method,
                url: req.url,
                headers: req.uiHeaderLines,
                body: (req.body) ? req.body : '',
                dateTouched: new Date().getTime(),
                isNewBundle: true
            });
    
            this.bundleAdmin.editor.saveButton.style.display = 'none';
            this.bundleAdmin.editor.saveLoadButton.style.display = 'none';
            this.bundleAdmin.editor.saveExitButton.style.display = '';
            this.bundleAdmin.editor.loadButton.style.display = 'none';
            this.bundleAdmin.editor.closeButton.style.display = '';
            this.bundleAdmin.editor.deleteButton.style.display = 'none';
            //so the save buttons are enabled
            this.bundleAdmin.editor.name.dispatchEvent(
                new CustomEvent('value-changed')
            );    
        }
    }
    /**
     * Show the admin div witht option tab to be selected. By default tab 0 will be displayed. All tabs will
     * be loaded fresh on each show of admin except for bundle admin which gets shown everytime the tab
     * is selected (see above on selected-changed event). 
     * @param {Number} selected - optional
     */
    _show(selected) {
        document.documentElement.style.overflow = 'hidden';
        if(selected) {
            this.tabs.selected = selected;
            this.pages.selected = selected;
        } else {
            this.tabs.selected = 0;
            this.pages.selected = 0;
        }
        
        // console.log(document.documentElement.style);
        // console.log(document.documentElement.style);
        // console.dir(document.documentElement.style);
        
        this.adminDiv.classList.add('fade-visible');
        this.adminDiv.classList.remove('fade-hidden');
        this.textAreaUrls.value = persistence.listURLs().join('\n');
        this.textAreaHeaders.value = persistence.listHeaders().join('\n');
        this.settings._loadSettings();
        //document.documentElement.style.overflow = 'hidden'; //disable scrolling on main document while this admin stuff is showing.

    }

    _close() {
        //re-enable scrolling on main doc
        this.adminDiv.classList.add('fade-hidden');
        this.adminDiv.classList.remove('fade-visible');
        this.tabs.selected = 0;
        this.pages.selected = 0;
        //if we leave largs amounts of data in these text area
        //it hurts performance... auto suggest gets glitchy.
        this.textAreaUrls.value = '';//persistence.listURLs().join('\n');
        this.textAreaHeaders.value = '';//persistence.listHeaders().join('\n');

        this.bundleAdmin._adminCloseCleanup();
        
        document.documentElement.style.overflowY = 'scroll';
    }

    _saveHeaders() {
        persistence.storeHeaders(this._toArrayAndFilter(this.textAreaHeaders.value), true);
        this.buttonHeaders.disabled = true;
    }

    _saveUrls() {
        persistence.storeURLs(this._toArrayAndFilter(this.textAreaUrls.value), true);
        this.buttonUrls.disabled = true;
    }



    _toArrayAndFilter(value) {
        return value.split('\n').filter(s => {
            return s.trim() !== '';
        });
    }
}

window.customElements.define('crest-admin', CRestAdmin);