import DataUtils, {
    REQUEST_TYPE_GET,
    REQUEST_TYPE_PUT,
    REQUEST_TYPE_POST,
    REQUEST_TYPE_DELETE,
    CONTENT_TYPE_JSON,
    CONTENT_TYPE_FORM
} from './DataUtils';
import * as DataEvent from '../events/DataEvent';
import {
    position,
    offset
} from 'caret-pos';

class TextEditor {

    //--------------------------
    // constructor
    //--------------------------
    constructor() {
        this.setInputs();
        hljs.initHighlightingOnLoad();
        this.dataUtils = new DataUtils();
        this.url = '';
        window.addEventListener("scroll", f => {
            var fixLimit = document.getElementById('header').offsetHeight + document.getElementById('entry-header').offsetHeight + document.getElementById('entry-feature').offsetHeight
            if (window.pageYOffset >= fixLimit) {
                document.getElementById('edit-control').style.position = "fixed"
            } else {
                document.getElementById('edit-control').style.position = "relative"
            }
        });
        this.refresh();
    }
    //--------------------------
    // methods
    //--------------------------
    setInputs() {
        let self = this;
        var editorButtons = document.querySelectorAll('.editor-button');
        for (var i = 0, length = editorButtons.length; i < length; i++) {
            editorButtons[i].addEventListener('click', e => this.handleEditorOption(e), false);
        }
        document.getElementById('edit-text-code').addEventListener('input', f => {
            self.refresh();
        })

        document.getElementById('post-image').addEventListener('change', e => this.handlePostImageAdd(e), false);
        document.getElementById('option-image').addEventListener('click', e => {
            document.getElementById('post-image').click();
        })
    }

    refresh() {
        var caret = position(document.getElementById('edit-text-code')).pos;
        var spiffed = hljs.highlight('markdown', document.getElementById('edit-text-code').innerText).value;
        var temp = document.createElement("div");
        temp.innerText = spiffed;
        document.getElementById('edit-text-code').innerHTML = temp.innerText;
        position(document.getElementById('edit-text-code'), caret)
    }

    //--------------------------
    // event handlers
    //--------------------------
    handleEditorOption(e) {
        e.preventDefault();
        var self = this;
        var sel, range, pulled;
        sel = window.getSelection(); //console.log(sel)
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            pulled = sel.getRangeAt(0).toString();
            range.deleteContents();
            switch (e.target.id) {
                case "option-bold":
                    range.insertNode(document.createTextNode("**" + pulled + "**"));
                    break;
                case "option-italic":
                    range.insertNode(document.createTextNode("*" + pulled + "*"));
                    break;
                case "option-strikethrough":
                    range.insertNode(document.createTextNode("<del>" + pulled + "</del>"));
                    break;
                case "option-header1":
                    range.insertNode(document.createTextNode("# " + pulled));
                    break;
                case "option-header2":
                    range.insertNode(document.createTextNode("## " + pulled));
                    break;
                case "option-header3":
                    range.insertNode(document.createTextNode("### " + pulled));
                    break;
                case "option-link":
                    range.insertNode(document.createTextNode("[" + pulled + "](PASTE URL HERE)"));
                    break;
                case "option-date":
                    console.log("DATE UPDATE")
                    break
                default:
                    //range.insertNode(document.createTextNode("[" + self.url + "](PASTE URL HERE)"));
                    break;
            }
        }
        this.refresh()
    }

    handlePostImageAdd(e) {
        e.stopPropagation();
        e.preventDefault();
        let self = this;

        var postData = new FormData();
        var files = e.target.files;
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            // Check the file type.
            if (!file.type.match('image.*')) {
                continue;
            }
            postData.append('post_image', file, file.name);
        }
        var caret = position(document.getElementById('edit-text-code')).pos;
        self.dataUtils.request("/api/blog/add-post-image", DataEvent.POST_IMAGE_ADDED, REQUEST_TYPE_POST, CONTENT_TYPE_FORM, postData)
            .then((response) => {
                //console.log("01 "+response.request['response']);
                position(document.getElementById('edit-text-code'), caret)
                var sel, range, pulled;
                sel = window.getSelection(); //console.log(sel)
                //console.log(note.message)
                if (sel.rangeCount) {
                    range = sel.getRangeAt(0);
                    pulled = sel.getRangeAt(0).toString();
                    range.deleteContents();
                    range.insertNode(document.createTextNode("![image alt text](" + JSON.parse(response.request['response']).url + " 'image title')"));
                }
                self.refresh();

            }).catch((err) => {
                console.log(err)
            })

    }
}
export default TextEditor