if (Scrollbar === undefined) {
    const { Scrollbar } = require("./ext_libs/js-scrollbar");
}

class UploadTool extends BaseObject {
    constructor(w = "ModalBox", c = null) {
        super();
        /*Variable */
        this.nav_ToolUpload = new Nav_ToolUpload(this);
        this.breadCrumb = new Breadcrumb(this);
        this.listFolder = new ListFolder(this);
        this.uploadExt = new UploadFileExt(this);
        this.stackEvent = Array.from([]);
        this.IsContainer = false;
        /*Init Control*/
        if (w == "ModalBox") {
            this.overlay = this.createOverlay();
            document.body.appendChild(this.overlay);
            Scrollbar.init(this.scrollContent, window.oScroll);
        } else {
            this.IsContainer = true;
            this.overlay = c;
            this.overlay.appendChild(this.createWrapper());
        }
        /*Init Scroolbar*/
        Scrollbar.init(this.containerScrollF, window.oScroll);

        /*Init Breadcrumb*/
   

        /*Innit NavToop Upload*/
        this.nav_ToolUpload.InitEventItem();
        this.uploadExt.Init();

        /*Init Dropdown when create tool upload*/
        this.dropdown = new Dropdown();
        this.dropdown.bindDropDowns(this.overlay.querySelectorAll(".dropdown"), "tUpload");

        /*Init ListFolder*/
        this.listFolder.InitMansory();

        /**/
        Waves.attach(".u-overlay .btn", "waves-effect");
    }
    dispose() {
        if (this.scrollContent != null) {
            Scrollbar.destroy(this.scrollContent);
        }
        Scrollbar.destroy(this.containerScrollF);
        this.dropdown.dispose();
        this.nav_ToolUpload.dispose();
        this.breadCrumb.dispose();
        this.listFolder.dispose();
        this.uploadExt.dispose();
        super.dispose();
        if (this.IsContainer) {
            for (var i = this.overlay.childNodes.length - 1; i >= 0; i--) {
                this.overlay.childNodes[i].remove();
            }
        } else {
            this.overlay.remove();
        }
        return null;

    }
    createOverlay() {
        var c = document.createElement("div");
        c.classList.add("u-overlay");
        this.scrollContent = this.createContainerScroll();
        c.appendChild(this.scrollContent);
        return c;
    }
    createContainer() {
        var c = document.createElement("div");
        c.classList.add("u-container", "d-f", "j-c-center", "a-i-center");
        c.appendChild(this.createWrapper());
        return c;
    }
    createContainerScroll() {
        var c = document.createElement("div");
        c.classList.add("u-scroll");
        c.appendChild(this.createContainer());
        return c;
    }
    mbCreateFolder() {
        var c = document.createElement("div");
        c.setAttribute("zIndex", "11000");
        c.setAttribute("data-id", "modalCreateFolder");
        c.classList.add("modal", "d-f", "a-i-center");
        var m = document.createElement("div");
        m.classList.add("modal-content");
        var t = document.createElement("div");
        t.classList.add("d-f", "f-c");
        var t1 = document.createElement("div");
        t1.classList.add("d-f", "j-c-between", "mb-3");
        var t2 = document.createElement("h4");
        t2.innerHTML = "Tạo Thư Mục";
        t1.appendChild(t2);
        t2 = document.createElement("a");
        t2.setAttribute("data-id", "close");
        t2.setAttribute("href", "javascript:void(0)");
        var i = document.createElement("span");
        i.classList.add("atg", "atg-x");
        t2.appendChild(i);
        t1.appendChild(t2);
        t.appendChild(t1);
        i = document.createElement("input");
        i.setAttribute("data-id", "txtFolder");
        i.setAttribute("placeholder", "Nhập tên thư mục");
        i.classList.add("form-control");
        t.appendChild(i);
        t1 = document.createElement("button");
        t1.innerHTML = "Tạo mới";
        t1.setAttribute("data-id", "btApply")
        t1.classList.add("btn", "btn-primary", "mt-3", "ml-auto");
        t.appendChild(t1);
        m.appendChild(t);
        c.appendChild(m);
        return c;
    }
    createWrapper() {
        var cls = "u-wrapper";
        if (this.IsContainer) {
            cls = "u-n-wrapper"
        }
        var b = document.createElement("div");
        b.classList.add(cls);
        b.appendChild(this.nav_ToolUpload.createNav());
        this.containerScrollF = this.createContainerScrollF();
        b.appendChild(this.containerScrollF);
        b.appendChild(this.mbCreateFolder());
        this.wrapper = b;
        return b;
    }
    createContainerScrollF = function () {
        var c = document.createElement("div");
        c.classList.add("u-c-file");
        var b = document.createElement("div");
        b.classList.add("u-row");
        b.appendChild(this.breadCrumb.CreateBreadcrumb());
        c.appendChild(b);
        c.appendChild(this.listFolder.CreateElementFolders());
        c.appendChild(this.listFolder.CreateElementFiles());
        return c;
    }
    LoadStorage(idStorage = 1) {
        const xhr = new XMLHttpRequest();
        xhr.open("POST", "/StorageManagement/GetStorage");
        xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8');
        var data = {
            "idStorage": idStorage
        };
        var f = function (e) {
            if (e.currentTarget.readyState == 4 && e.currentTarget.status == 200) {
                var tm = JSON.parse(e.currentTarget.responseText);
                if (tm.type == "success") {
                    this.breadCrumb.AddItem(false, "My Files", tm.res.idF);
                    this.breadCrumb.on("itemClick", this.BreadCrumb_ItemClick.bind(this));
                    this.LoadFolder(tm.res.idF);
                }
        
            }
        }.bind(this);
        xhr.addEventListener("readystatechange", f, false);
        xhr.send(JSON.stringify(data));
    }
    LoadStorageByF(id) {
        this.breadCrumb.AddItem(false, "My Files", id);
        this.breadCrumb.on("itemClick", this.BreadCrumb_ItemClick.bind(this));
        this.LoadFolder(id);
    }
    LoadFolder(idF) {
        const xhr = new XMLHttpRequest();
        xhr.open("POST", "/StorageManagement/GetFolder");
        xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8');
        var data = {
            "idFolder": idF
        };
        var f = function (e) {
            if (e.currentTarget.readyState == 4 && e.currentTarget.status == 200) {
                var tm = JSON.parse(e.currentTarget.responseText);
                if (tm.type == "success") {
                    Array.from(tm.res).forEach(el => {
                        this.listFolder.addItem({ "name": el.name, "count": el.count, "code": el.code, "id": el.id });
                    });
                    this.listFolder.mansory.layout();
                    this.listFolder.mansory.reloadItems();
                }
            }
        }.bind(this);
        xhr.addEventListener("readystatechange", f, false);
        xhr.send(JSON.stringify(data));
    }
    BreadCrumb_ItemClick(e) {
        this.listFolder.RemoveActiveItem();
        this.listFolder.RemoveAllList();
        this.LoadFolder(e.getAttribute("data-id"));
    }
}

class UploadFileExt extends BaseObject {
    constructor(tUpload) {
        super();
        this.parent = tUpload;
        this.listInputF = Array.from([]);
        this.listF = Array.from([]);
        this.count = 0;
        this.worker = undefined;
        window.uploadExt = this;
    }
    Init()
    {
        this.CreateSlideBar();
        this.parent.containerScrollF.appendChild(this.container);
    }
    dispose() {
        super.dispose();
        Scrollbar.destroy(this.scrollC);
    }
    AddInputFile() {
        this.count += 1;
        var f = document.createElement("input");
        f.setAttribute("type", "file");
        f.setAttribute("name", "f" + this.count + "[]");
        f.setAttribute("multiple", "");
        this.cfile.appendChild(f);
        this.listInputF.push(f);
        var fe = function (e) {
            this.ChangeInputFile.call(this, f, e);
        }.bind(this);
        f.addEventListener("change", fe, false);
        this.stackEvent.push({ "event": "change", "callback": fe, "element": f, "parent": "InputFile" });
        f.click();
    }
    RemoveAllInputFile() {
        this.RemoveEventParent("InputFile");
        this.listInputF.forEach(e => {
            e.remove();
        })
        this.listInputF = [];
        this.listF = [];
        this.count = 0;
        this.activeSlide = false;
        this.RemoveEventParent("XHR");
        this.RemoveEventParent("InputFile");
    }
    StartUploading() {
        if (this.listF.length == 0) {
            this.btStartUpload.RemoveLoading(document.getElementById("btStartUpload"));
            return;
        }
        window.countUp = 0;
        this.CheckFileBucket();
        this.parent.nav_ToolUpload.HideItemNav("ufile");
        if (typeof (Worker) !== "undefined") {
            if (typeof (this.worker) == "undefined") {
                this.worker = new Worker("/js/js-upload-worker.js");
                this.worker.postMessage({ status: "StartUpload", totalF: this.listF.length});
                var f = function (e) {
                    this.WorkerEvent.call(this, e);
                }.bind(this);
                this.worker.addEventListener("message", f, false);
            }
        }
    }
    PopFileUpload() {
        var it = this.scrollContent.querySelector(".item:first-child");
        if (it == null) {
            this.worker.postMessage({ status: "NoItem" });
        } else {
            it.remove();
        }
    }
    WorkerEvent(e) {
        if (e.data == "Upload") {
            window.countUp += 1;
            this.CheckFileBucket();
        }
        else if (e.data == "Tick")
        {
            this.PopFileUpload();
        }
        else if (e.data == "Uploaded")
        {
            this.RemoveAllInputFile();
        }
        else
        {
            this.worker.terminate();
            this.worker = undefined;
            this.btStartUpload.RemoveLoading(document.getElementById("btStartUpload"));
            this.parent.nav_ToolUpload.ShowItemNav("ufile");
        }
    }
    EventUploaded(e, item, bucket) {
        if (e.target.responseText == "\"OK\"") {
            var it = this.scrollContent.querySelector("[data-id=" + item.FileID + "]");
            var p = it.querySelector(".upl-des .percent");
            p.innerHTML = "File Uploaded";
            p = it.querySelector(".upl-des span:last-child");
            p.remove();
            window.bucket[bucket] = 1;
            this.worker.postMessage({ status: "Uploaded", bucket:window.bucket });
        }
    }
    EventUploading(e, item) {
        var per = parseInt(e.loaded / e.total * 100);
        var it = this.scrollContent.querySelector("[data-id=" + item.FileID + "]");
        var progressbar = it.querySelector(".c-progress .value");
        progressbar.style.width = per + "%";
        var p = it.querySelector(".upl-des .percent");
        p.innerHTML = per + "%&nbsp";
    }
    CheckFileBucket() {
        if (this.listF.length <= 4) {
            this.FileUploading(0, this.listF.length);
        } else {
            var t1 = window.countUp * 4;
            if ((window.countUp + 1) * 4 > this.listF.length) {
                this.FileUploading(t1, this.listF.length);
            } else {
                this.FileUploading(t1, t1 + 4);
            }
           
        }
    }
    FileUploading(idx, e_idx) {
        //Init Bucket
        window.bucket = [];
        var x = e_idx - idx;
        for (var i = 0; i < x; i++) {
            window.bucket.push(0);
        }
        for (var i = idx; i < e_idx; i++) {
            var item = this.listF[i];
            var xhr = new XMLHttpRequest();
            var formdata = new FormData();
            formdata.append("File", item.File);
            formdata.append("FolderID", this.parent.breadCrumb.getLastItemId());
            formdata.append("FileType", item.FileType);
            formdata.append("Type", item.Type);
            formdata.append("FileSize", item.FileSize);
            formdata.append("FileName", item.FileName);
            xhr.open("POST", "/StorageManagement/UploadFileAsync");
            (function (a, b) {
                var f = function (e) {
                    this.EventUploaded.call(this, e, a, b);
                }.bind(this);
                xhr.addEventListener("load", f, false);
                this.stackEvent.push({ "event": "load", "callback": f, "element": xhr, "parent": "XHR" });
            }.bind(this))(item, ((e_idx - 1) - i))

            if (xhr.upload) {
                (function (a) {
                    var f1 = function (e) {
                        if (e.lengthComputable) {
                            this.EventUploading.call(this, e, a);
                        }
                    }.bind(this);
                    xhr.upload.addEventListener("progress", f1, false);
                    this.stackEvent.push({ "event": "progress", "callback": f1, "element": xhr.upload, "parent": "XHR" });
                }.bind(this))(item);
              
            }
            xhr.send(formdata);
        }
    }
    ChangeInputFile(inp, e) {
        if (this.activeSlide) {
            this.activeSlide = false;
            this.container.classList.add("show");
        }
        for (var i = 0; i < inp.files.length; i++) {
            var f = inp.files[i];
            if (this.CheckExistFile(f.name)) {
                continue;
            }
            var str = f.name.split('.');
            var ftype = str[str.length - 1];
            str.splice(str.length - 1, 1);
            var fExt = this.GetFileSize(f.size);
            var nInp = inp.getAttribute("name");
            var fi = {
                FileID: nInp.substring(0, nInp.length - 2) + i,
                FileName: str.join(""),
                File: f,
                FileType: ftype,
                Type: f.type,
                FileSizeS: fExt,
                FileSize: f.size
            };
            this.listF.push(fi);
            this.AddItemFile(fi);
        }
    }
    CheckExistFile(n) {
        for (var i = 0; i < this.listF.length; i++) {
            if (this.listF[i].File.name === n) {
                return true;
            }
        }
    }
    AddItemFile(fi) {
        var d = document.createElement("div");
        d.classList.add("d-f", "f-c", "item");
        d.setAttribute("data-id", fi.FileID);
        var d1 = document.createElement("div");
        d1.classList.add("d-f", "c-text");
        d.appendChild(d1);
        var s = document.createElement("span");
        s.classList.add("text-infor", "ellipsis");
        s.innerHTML = fi.FileName;
        d1.appendChild(s);
        s = document.createElement("span");
        s.classList.add("text-infor");
        s.innerHTML = ".";
        d1.appendChild(s);
        s = document.createElement("span");
        s.classList.add("text-infor");
        s.innerHTML = fi.FileType;
        d1.appendChild(s);
        s = document.createElement("a");
        s.classList.add("ml-2");
        s.setAttribute("href", "javascript:void(0)");
        var ic = document.createElement("span");
        ic.classList.add("atg", "atg-rename");
        s.appendChild(ic);
        d1.appendChild(s);
        s = document.createElement("a");
        s.classList.add("ml-auto");
        s.setAttribute("href", "javascript:void(0)");
        ic = document.createElement("span");
        ic.classList.add("atg", "atg-x");
        s.appendChild(ic);
        d1.appendChild(s);
        d.appendChild(this.CreateProgressBar());
        d1 = document.createElement("div");
        d1.classList.add("d-f", "mt-2", "upl-des");
        d.appendChild(d1);
        s = document.createElement("span");
        s.classList.add("percent");
        s.innerHTML = "0%&nbsp";
        d1.appendChild(s);
        s = document.createElement("span");
        s.innerHTML = "of " + fi.FileSizeS;
        d1.appendChild(s);
        this.scrollContent.appendChild(d);
    }
    CreateProgressBar() {
        var d = document.createElement("div");
        d.classList.add("c-progress", "mt-2", "mr-4");
        var d1 = document.createElement("div");
        d1.classList.add("value");
        d1.setAttribute("style", "width:0%");
        d.appendChild(d1);
        return d;
    }
    GetFileSize(n) {
        var fSExt = new Array('Byte', 'Kb', 'Mb', 'Gb');
        var j = 0;
        while (n > 900) {
            n /= 1024;
            j++;
        }
       return (Math.round(n * 100) / 100) + " " + fSExt[j];
    }
    CreateSlideBar() {
        var a = document.createElement("div");
        a.classList.add("con-slide-upload");
        this.container = a;
        a = document.createElement("div");
        a.classList.add("d-n", "c-files");
        this.container.appendChild(a);
        this.cfile = a;
        a = document.createElement("div");
        a.classList.add("slide-upload", "h-100");
        this.container.appendChild(a);
        var c = document.createElement("div");
        c.classList.add("d-f", "a-i-center", "c-slide-header");
        a.appendChild(c);
        var b = document.createElement("button");
        b.classList.add("btn", "btn-effect", "btn-primary", "waves-effect", "waves-float");
        b.innerHTML = "Start Upload";
        b.setAttribute("id", "btStartUpload");
        c.appendChild(b);
        var bt = new AButton(b);
        this.btStartUpload = bt;
        bt.on("click_btStartUpload", function (e) {
            this.StartUploading();
        }.bind(this));
        b = document.createElement("a");
        b.classList.add("sl-close", "ml-auto");
        c.appendChild(b);
        var ic = document.createElement("span");
        ic.classList.add("atg", "atg-x");
        b.appendChild(ic);
        c =  document.createElement("h4");
        c.classList.add("header");
        c.innerHTML = "Progress Upload";
        a.appendChild(c);
        c = document.createElement("div");
        c.classList.add("scroll-slide-upload");
        a.appendChild(c);
        this.scrollC = c;
        Scrollbar.init(this.scrollC, window.oScroll);
        this.scrollContent = c.querySelector(".scroll-content");
        var m = document.createElement("div");
        m.classList.add("d-f", "f-c");

    }
}

class ListFolder extends BaseObject {
    constructor(tUpload) {
        super();
        this.activeItem = null;
        this.multiActiveItem = [];
        this.parent = tUpload;
        window.listF = this;

        this.scrollF = Scrollbar.get(this.parent.containerScrollF);
    }
    dispose() {
        this.mansory.destroy();
        this.mFile.destroy();
        super.dispose();
    }
    InitMansory() {
        this.mansory = new Masonry('.grid-folder', {
            itemSelector: '.grid-item',
            columnWidth: '.grid-sizer',
            percentPosition: true
        });
        this.mFile = new Masonry(".grid-file", {
            itemSelector: '.grid-item',
            columnWidth: '.grid-sizer',
            percentPosition: true
        });
        this.AddTest();
        var f = function (e) {
            this.EventFolderClick.call(this, e);
        }.bind(this);
        this.parent.containerScrollF.addEventListener("click", f, false);
        this.stackEvent.push({ "event": "click", "callback": f, "element": this.parent.containerScrollF, "parent": null });
    }
    AddTest() {
        this.listFiles = [];
        Scrollbar.get(this.parent.containerScrollF).destroy();
        var list = this.AddTestFile();
        list.forEach(el => {
            this.addItemFile(el);
        });
        var work = new Worker("/js/js-stackimage.js");
        work.addEventListener("message", function (e) {
            var mess = e.data;
            if (mess.status == "ElementLoading") {
                requestTimeout((() => {
                    const objectURL = URL.createObjectURL(mess.data.blob);
                    this.listFiles[mess.data.index].setAttribute("src", objectURL);
                    work.postMessage({ "status": "ElementLoaded" });
                }).bind(this), 50, window.registerCancel);
               
            } else if (mess.status == "Completed") {
                work.terminate();
                requestTimeout(() => {
                    Scrollbar.init(this.parent.containerScrollF, window.oScroll);
                }, 1000, window.registerCancel);
            }
        }.bind(this));
        requestTimeout(() => { work.postMessage({ "status": "Start", "data": list }); }, 1000, window.registerCancel);
    }
    AddTestFile() {
        var file = [
            { "url": "/images/test/1.png", "rate": "1.32" },
            { "url": "/images/test/2.jpg", "rate": "1.77" },
            { "url": "/images/test/3.jpg", "rate": "1", "encode": "" },
            { "url": "/images/test/4.jpg", "rate": "0.75", "encode": "" },
            { "url": "/images/test/5.jpg", "rate": "0.75", "encode": "" },
            { "url": "/images/test/6.jpg", "rate": "0.75", "encode": "" },
            { "url": "/images/test/7.jpg", "rate": "0.75", "encode": "" },
            { "url": "/images/test/8.jpg", "rate": "0.75", "encode": "" },
            { "url": "/images/test/9.png", "rate": "1", "encode": "" },
        ];
        return file;
    }
    EventFolderClick(e) {
        if (e.target.classList.contains("conFolder") || e.target.classList.contains("folder")) {
            this.RemoveActiveItem();
            var t = e.target.closest(".conFolder");
            t.classList.add("active");
            this.activeItem = t;
            this.multiActiveItem.push(t);
        }
        else if (e.target.closest(".btCon") != null) {
            var t = e.target.closest(".conFolder");
            t.classList.add("active");
            this.multiActiveItem.push(t);
            this.activeItem = t;
        }
        else if (e.target.closest(".conImg") != null || e.target.classList.contains("folderName")) {
            var t = e.target.closest(".conFolder");
            var fn = t.querySelector(".folderName");

            this.parent.breadCrumb.AddItem(true, fn.innerHTML, t.getAttribute("data-id"));
            this.parent.LoadFolder(t.getAttribute("data-id"));
            this.RemoveActiveItem();
            this.RemoveAllList();
        }
        else
        {
            this.RemoveActiveItem();
            this.RemoveAllItem();
        }
    }
    RemoveActiveItem() {
        if (this.activeItem) {
            this.activeItem.classList.remove("active");
            this.activeItem = null;
        }
        if (this.multiActiveItem) {
            this.RemoveAllItem();
        }
    }
    RemoveAllItem() {
        while (this.multiActiveItem.length != 0) {
            var t = this.multiActiveItem.pop()
            t.classList.remove("active");
        }
    }
    RemoveAllList() {
        var listGrid = this.container.querySelectorAll(".grid-item");
        Array.from(listGrid).forEach(el => {
            this.mansory.remove(el);
        });
    }
    CreateElementFolders() {
        var c = document.createElement("div");
        c.classList.add("grid-folder");
        var c1 = document.createElement("div");
        c1.classList.add("grid-sizer");
        c.appendChild(c1);
        this.container = c;
        return c;
    }
    CreateElementFiles() {
        var c = document.createElement("div");
        c.classList.add("grid-file");
        var c1 = document.createElement("div");
        c1.classList.add("grid-sizer");
        c.appendChild(c1);
        this.containerF = c;
        return c;
    }
   
    addItemFile(o) {
        var c = document.createElement("div");
        c.classList.add("grid-item");
        var ic = document.createElement("div");
        ic.classList.add("conFile", "d-f", "f-c", "a-i-center", "j-c-center");
        var pv = document.createElement("div");
        pv.classList.add("imagePreview");
        var cInfor = document.createElement("div");
        cInfor.classList.add("cInfor");
        pv.appendChild(cInfor);
        var img = document.createElement("img");
        img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8Xw8AAoMBgDTD2qgAAAAASUVORK5CYII=";
        img.setAttribute("data-url", o.url);
        this.listFiles.push(img);
        pv.appendChild(img);
        ic.appendChild(pv);
        c.appendChild(ic);
        this.containerF.appendChild(c);
        ic.style.height = ic.clientWidth + "px";
        if (o.rate < 1) {
            var t = getComputedStyle(ic);
            img.style.width = ((ic.clientHeight - parseInt(t.paddingTop) - parseInt(t.paddingBottom)) * o.rate) + "px";
            pv.style.width = img.style.width;
        } 
        this.mFile.appended(c);
    }
    addItem(o) {
        var c = document.createElement("div");
        c.classList.add("grid-item");
        var ic = document.createElement("div");
        ic.classList.add("conFolder", "d-f", "f-c", "a-i-center");
        ic.setAttribute("data-code", o.code);
        ic.setAttribute("data-id", o.id)
        var btCon = document.createElement("div");
        btCon.classList.add("btCon", "j-c-center", "a-i-center");
        var btS = document.createElement("div");
        btS.classList.add("btSelect", "d-f", "a-i-center", "j-c-center");
        var icTick = document.createElement("span");
        icTick.classList.add("atg", "atg-tick");
        btS.appendChild(icTick);
        btCon.appendChild(btS);
        ic.appendChild(btCon);
        var cf = document.createElement("div");
        cf.classList.add("folder", "d-f", "j-c-center");
        var ci = document.createElement("div");
        ci.classList.add("conImg");
        var im = document.createElement("img");
        im.setAttribute("src", "/images/upload/folder.svg");
        var im1 = document.createElement("img");
        im1.classList.add("folder-front");
        im1.setAttribute("src", "/images/upload/folder_front.svg");
        var nf = document.createElement("span");
        nf.innerHTML = o.count;
        nf.classList.add("numF");
        ci.appendChild(nf);
        ci.appendChild(im);
        if (o.count > 0) {
            var hf = document.createElement("div");
            hf.classList.add("have-file");
            ci.appendChild(hf); 
        }
        ci.appendChild(im1);
        cf.appendChild(ci);
        var h = document.createElement("h5");
        h.classList.add("folderName");
        h.innerHTML = o.name;
        ic.appendChild(cf);
        ic.appendChild(h);
        c.appendChild(ic)
        this.container.appendChild(c);
        im.style.minHeight = (ci.clientWidth * 0.73) + "px";
        this.mansory.appended(c);
    }
    
}

class Breadcrumb extends BaseObject {
    constructor(tUpload) {
        super();
        this.parent = tUpload;
        this.history = Array.from([]);
    }
    itemMenu() {
        var c = document.createElement("div");
        c.classList.add("citem");
        c.setAttribute("data-dropdown", "");
        c.setAttribute("data-control", "m-breadcrumb");
        var a = document.createElement("a");
        a.classList.add("dropdown");
        a.setAttribute("href", "javascript:void(0)");
        a.setAttribute("data-item", "")
        var i = document.createElement("span");
        i.classList.add("atg", "atg-dot");
        a.appendChild(i);
        c.appendChild(a);
        var s = document.createElement("div");
        s.classList.add("sub-item", "d-f", "f-c");
        this.subItemE = s;
        c.appendChild(s);
        c.style.display = "none";
        return c;
    }
    RaiseEventItemClick(e) {
        var el = e.currentTarget;
        var l = this.parent.overlay.querySelector(".breadcrumb > .item:last-child");
        if (el.classList.contains("nonhide")) {
            this.parent.dropdown.CloseDropdown();
        }
        if (el != l) {
            do {
                var s = el.nextSibling;
                if (s == null) {
                    break;
                } else {
                    this.RemoveEvent(s);
                }
                s.remove();
            } while (true);
            var t = Array.from(this.parent.overlay.querySelectorAll(".breadcrumb > .item"));
            var s = Array.from(this.parent.overlay.querySelectorAll(".breadcrumb > .sep"));
            var t1 = Array.from(this.parent.overlay.querySelectorAll(".breadcrumb .sub-item > .item"));
            if (el.parentNode.classList.contains("sub-item")) {
                t.forEach(e1 => {
                    this.RemoveEvent(e1);
                    e1.remove();
                })
                s.forEach(e1 => {
                    e1.remove();
                })
            }
            this.popSubITem(t, s, t1);
            if (this.BreadcrumbE.children[this.BreadcrumbE.children.length - 1].classList.contains("sep")) {
                this.BreadcrumbE.children[this.BreadcrumbE.children.length - 1].remove();
            }
            this.trigger("itemClick", el);
        }
    }
    popSubITem(t, s, t1) {
        var ws = this.getWidthSeperate((s.length > 0) ? s[0] : null);
        var w = this.calcTotalWidth(t) + (s.length * ws);
        if (this.subItemE.childNodes.length > 0) {
            w += this.itemMenuE.offsetWidth;
        }
        var tw = this.BreadcrumbE.offsetWidth;
      
        do {
            if (t1.length == 0) {
                this.itemMenuE.style.display = "none";
                break;
            };
            var t2 = t1.pop();
            t2.style.visibility = "hidden";
            this.BreadcrumbE.insertBefore(t2, this.BreadcrumbE.children[1]);
            w += t2.offsetWidth + ws;
            if (w <= tw) {
                var s = document.createElement("span");
                s.classList.add("atg", "atg-more", "sep");
                this.BreadcrumbE.insertBefore(s, this.BreadcrumbE.children[2]);
                t2.style.visibility = "visible";
                t2.classList.remove("nonhide");
                continue;
            } else {
                t2.style.visibility = "visible";
                this.subItemE.appendChild(t2);
                break;
            }
        } while (true);

    }
    CreateBreadcrumb() {
        var c = document.createElement("div");
        c.classList.add("breadcrumb", "d-f", "a-i-center");
        this.itemMenuE = this.itemMenu();
        c.appendChild(this.itemMenuE);
        this.BreadcrumbE = c;
        return c;
    }
    AddItem(h, name, idF) {
        var f = document.createDocumentFragment();
        var c = document.createElement("a");
        c.classList.add("item");
        c.setAttribute("title", name);
        c.setAttribute("href", "javascript:void(0)");
        c.setAttribute("data-control", "bItem");
        c.setAttribute("data-id", idF);
        c.innerHTML = name;
        this.hiddenElement(c);
        f.appendChild(c);
        this.BreadcrumbE.appendChild(f);
        if (c.offsetWidth > 160) {
            c.classList.add("ellipsis");
        }
        if (h) {
            var s = document.createElement("span");
            s.classList.add("atg", "atg-more", "sep");
            this.hiddenElement(s);
            this.BreadcrumbE.insertBefore(s, this.BreadcrumbE.children[this.BreadcrumbE.children.length - 1]);
            this.checkWidthItem();
            this.showElement(s);
        }
        var k = function (ev) {
            this.RaiseEventItemClick.call(this, ev);
        }.bind(this);
        c.addEventListener("click", k, false);
        this.stackEvent.push({ "event": "click", "callback": k, "element": c, "parent": null });
        this.showElement(c);
    }
    checkWidthItem() {
        var t = Array.from(this.parent.overlay.querySelectorAll(".breadcrumb > .item"));
        var s = Array.from(this.parent.overlay.querySelectorAll(".breadcrumb > .sep"));
        var ws = this.getWidthSeperate((s.length > 0) ? s[0] : null);
        var w = this.calcTotalWidth(t) + (s.length * ws);
        if (this.subItemE.childNodes.length > 0) {
            w += this.itemMenuE.offsetWidth;
        }
        var tw = this.BreadcrumbE.offsetWidth;
        while (w > tw) {
            var t1 = t.shift();
            var s1 = s.shift();
            if (s1 != null) s1.remove();
            t1.classList.add("nonhide");
            this.subItemE.appendChild(t1);
            w -= (t1.offsetWidth + ws);
            this.MoveItemToSub(t1);
        }
    }
    getLastItem() {
        return this.parent.overlay.querySelector(".breadcrumb > .item:last-child");
    }
    getLastItemId() {
        return this.getLastItem().getAttribute("data-id");
    }
    calcTotalWidth(b) {
        var w = 0;
        b.forEach(e => {
            w += e.offsetWidth;
        });
        return w;
    }
    getWidthSeperate(e) {
        if (e != null) {
            return e.offsetWidth;
        }
        return 0;
    }
    MoveItemToSub(a) {
        if (this.itemMenuE.style.display == "none") this.itemMenuE.style.display = "block";
    }
    hiddenElement(e) {
        e.style.visibility = 'hidden';
    }
    showElement(e) {
        e.style.visibility = 'visible';
    }
}

class Nav_ToolUpload extends BaseObject {
    constructor(tUpload) {
        super();
        this.parent = tUpload;
    }
    InitEventItem() {
        var k = function (ev) {
            this.EventCreateFolder.call(this, ev);
        }.bind(this);
        var e = this.parent.overlay.querySelector("[data-id=cfolder]");
        e.addEventListener("click", k, false);
        this.stackEvent.push({ "event": "click", "callback": k, "element": e, "parent": "Nav" });
        e = this.parent.overlay.querySelector("[data-id=ufile]");
        k = function (ev) {
            this.EventUploadFile.call(this, ev);
        }.bind(this);
        e.addEventListener("click", k, false);
        this.stackEvent.push({ "event": "click", "callback": k, "element": e, "parent": "Nav" });
    }
    createbtClose() {
        var c = document.createElement("a");
        c.setAttribute("href", "javascript:void(0)");
        c.classList.add("bt-close", "ml-auto");
        var s = document.createElement("span");
        s.classList.add("atg", "atg-x");
        c.appendChild(s);
        return c;
    }
    HideItemNav(id)
    {
        var t = document.querySelector(".nav-tupload .item[data-id=" + id + "]");
        t.classList.add("d-n");
    }
    ShowItemNav(id)
    {
        var t = document.querySelector(".nav-tupload .item[data-id=" + id + "]");
        t.classList.remove("d-n");
    }
    createNav() {
        var c = document.createElement("div");
        c.classList.add("container-tupload");
        var n = document.createElement("div");
        n.classList.add("d-f", "nav-tupload")
        n.appendChild(this.addItemNav("plus", "Tạo mới", this.addSubItemNav([{ "id": "cfolder", "name": "Thư mục" }, { "id": "ctext", "name": "Text Document" }])));
        n.appendChild(this.addItemNav("upload", "Tải lên", this.addSubItemNav([{ "id": "ufile", "name": "Tải tệp" }, { "id": "ufolder", "name": "Tải thư mục" }])));
        n.appendChild(this.addItemNav("moveto", "Di chuyển", null));
        n.appendChild(this.addItemNav("copy", "Sao chép", null));
        n.appendChild(this.addItemNav("rename", "Đổi tên", null));
        n.appendChild(this.addItemNav("delete", "Xóa", null));
        if (!this.parent.IsContainer) {
            n.appendChild(this.createbtClose());
        }
        c.appendChild(n);
        return c;
    }
    addItemNav(icon, name, subitem) {
        var c = document.createElement("div");
        c.setAttribute("data-control", "tUpload");
        var i = document.createElement("a");
        i.classList.add("item", "d-f");
        i.setAttribute("href", "javascript:void(0)");
        i.setAttribute("data-item-name", "i" + icon);
        var s = document.createElement("span");
        s.classList.add("atg", "atg-" + icon);
        i.appendChild(s);
        s = document.createElement("span");
        s.innerHTML = name;
        s.classList.add("name", "ml-2");
        i.appendChild(s);
        c.appendChild(i);
        if (subitem != null) {
            c.setAttribute("data-dropdown", "");
            s = document.createElement("span");
            s.classList.add("atg", "atg-down", "ml-2", "nonhide");
            i.appendChild(s);
            c.appendChild(subitem);
            i.classList.add("dropdown");
        }
        return c;
    }
    addSubItemNav(a) {
        var d = document.createElement("div");
        d.classList.add("sub-item", "d-f", "f-c");
        a.forEach(e => {
            var i = document.createElement("a");
            i.setAttribute("data-id", e.id);
            i.setAttribute("href", "javascript:void(0)");
            i.classList.add("item", "nonhide");
            i.innerHTML = e.name;
            d.appendChild(i);
        });
        return d;
    }
    EventCreateFolder(e) {
        if (e.currentTarget.classList.contains("d-n")) return;
        this.parent.dropdown.CloseDropdown();
        var mb = new ModalBox(this.parent.overlay.querySelector("[data-id=modalCreateFolder]"));
        mb.show();
        mb.once("close", this.processCreateFolder.bind(this));
    }
    EventUploadFile(e) {
        if (e.currentTarget.classList.contains("d-n")) return;
        this.parent.dropdown.CloseDropdown();
        this.parent.uploadExt.activeSlide = true;
        this.parent.uploadExt.AddInputFile();
        
    }
    EventUploadFolder(e) {
        if (e.currentTarget.classList.contains("d-n")) return;
        this.parent.dropdown.CloseDropdown();
        this.parent.uploadExt.activeSlide = true;
        this.parent.uploadExt.AddInputFile();
    }
    processCreateFolder(e) {
        var t = e.querySelector("[data-id=txtFolder]");
        var data = {
            "idFP": this.parent.breadCrumb.getLastItemId(),
            "Name": t.value
        };
        const xhr = new XMLHttpRequest();
        xhr.open("POST", "/StorageManagement/CreateFolder");
        xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8');
        var f = function (e) {
            if (e.currentTarget.readyState == 4 && e.currentTarget.status == 200) {
                var o = JSON.parse(e.currentTarget.responseText);
                if (o.type == "success") {
                    var res = o.res;
                    this.parent.listFolder.addItem({ "name": res.name, "count": res.count, "code": res.code, "id": res.id });
                } else {
                    //Ouput Error
                }
                xhr.removeEventListener("readystatechange", f);
            }
        }.bind(this);
        xhr.addEventListener("readystatechange", f, false);
        xhr.send(JSON.stringify(data));
    }
}
window.AScript["js-upload"] = { "loaded": true, "name":"js-upload.js"};