var urlCircle = [];
setInterval(function () {
    let currentUrl = window.location.href;
    if (urlCircle.length > 0 && urlCircle.shift() !== currentUrl) {
        init();
    }
    urlCircle.push(currentUrl)
    bindChangeImg();
}, 1000);

var body = $("#__nuxt");

var img = new Image();
var checkedProp = false;
img.src = chrome.extension.getURL("ui.html");
let icon = chrome.extension.getURL("static/icon.png");
var parentDom = document.createElement("div");
parentDom.innerHTML = "<div class='mpDonloaderParentDom'><img src='"+ icon +"'/></div>";
parentDom.onclick = () => {
    toggleButton();
}
body.append(parentDom);
var UI = chrome.extension.getURL("ui.html");
var isOpen = false;
var container = null;
var index = getIndex();


function init() {
    if (isOpen) {
        isOpen = false;
        toggleButton();
    }
}

bindChangeImg();
bindChangeWorkEvents();

function openUi() {
    var isFrist = true;
    $.get(UI, (html) => {
        container = $(html);
        let tpl = container.find("#tpl")[0].outerHTML;
        let images = getImages();
        var doms = [];
        for(var i in images) {
            if (isNaN(i)) {
                break;
            }
            var _  = $(tpl);
            $($(_).find("img")[0]).attr("src" , images[i].url + "!340w.jpg");
            if (isFrist) {
                $($(_).find("img")[0]).addClass("focus");
            }
            isFrist = false;
            $($(_).children().find("input[type=checkbox]")[0]).val(images[i].url);
            $($(_).children().find("input[type=checkbox]")[0]).attr("fileid", images[i].name);
            $($(_).find(".fileid")[0]).text(images[i].name);
            doms.push(_.html());
        };
        $(container.find(".images")[0]).html(doms.join(""));
        $.each(container.find(".item"), (i,n)  => {
            $(n).find("img")[0].onclick = () => {
                setSelect($(n).find("img")[0], images);
            };
        });
        $.each(container.find(".item"), (i,n)  => {
            $(n).find("img")[0].onclick = () => {
                setSelect($(n).find("img")[0], images);
            };
        });
        $(container).find(".selectAll")[0].onclick=function() {
            selectAll();
        };
        $(container).find(".startDownload")[0].onclick=function() {
            downloadAll();
        };
        body.append(container);
    });
}

function closeUi() {
    if (container !== null) {
        $(container).remove();
    }
}



function refreshIndex() {
    index = getIndex();
}

function toggleButton() {
    closeUi();
   if (isOpen === false) {
       openUi();
   }
   isOpen = !isOpen;
}

function setSelect(dom, all) {
    let src = dom.src.split("!")[0];
    let big = $(".swiper-slide-active").find("img")[0].src.split("!")[0];
    let images = [];
    let direction = "";
    $.each(all, (i,n)  => {
        images.push(n.url);
    });
    let index1 = images.indexOf(src);
    let index2 = images.indexOf(big);
    if (index1 < index2) {
        direction = ".btn-prev"
    }
    if (index1 > index2) {
        direction = ".btn-next"
    }
    if ($.trim(direction) !== "") {
        for (var i = 0;i<Math.abs(index1-index2);i++) {
            $(direction).click();
        }
    }
}

function getImages() {
    var worksId;
    var userNickname;
    var userId = "";
    var lists = [];
    var images = [];
    var reg = /\/\d{1,}\//g;
    var records = [];
    lists = $(".swiper-wrapper").find("img");
    var urls = [];
    var imgSrc = "";
    var worksString = window.location.href.match(/\works\/\S*\?/g);
    if (worksString.length > 0) {
        worksId = worksString[0].replace("works/", "");
        worksId = worksId.replace("?", "");
        worksId = base64Decode(worksId);
    }
    userNickname = $($(".user-info > span.nickname")[0]).text();

    $.each(lists, (i,n) => {
        urls = n.currentSrc.split("!");
        imgSrc = urls[0];
        if (imgSrc.indexOf("videos.mepai.me") < 0) {
            if (records.indexOf(imgSrc) < 0) {
                if (userId === "") {
                    var idStrings = imgSrc.match(reg);
                    if (idStrings !== undefined && idStrings.length > 0) {
                        userId = idStrings[0].replace(/\//g, "");
                    }
                }
                records.push(imgSrc);
                images.push({
                    name: worksId + "-" + userNickname + '-' +userId + "-" + index(),
                    url:   imgSrc
                });
            }
        }
    });
    refreshIndex();
    return images;
}

function base64Decode(input){
    rv = window.atob(input);
    rv = escape(rv);
    rv = decodeURIComponent(rv);
    return rv;
}

function selectAll() {
    checkedProp = !checkedProp;
    $($(body).find("input[type='checkbox']")).attr("checked", checkedProp);
}


function getCurrentImg() {
    var src = $("div.swiper-slide-active").find("img")[0].src;
    var urls = src.split("!");
    if (urls.length > 1) {
        return urls[0];
    }
    return src;
}

function changeFocus() {
    setTimeout(() => {
        var currentUrl = getCurrentImg();
        if (container == null) {
            return;
        }
        $($(container).find("img")).removeClass("focus");
        var imgs = $(container).find("img");
        for(var i in imgs) {
            if (imgs[i].src === currentUrl + "!340w.jpg") {
                $(imgs[i]).addClass("focus")
                break;
            }
        }
    }, 500);

}
function downloadAll() {
    if (confirm("点击确定开始下载!")) {
        var q = $("select[name=quality]").val();
        var ext = "";
        if (q == 720) {
            ext = "!720w.jpg";
        }
        $.each($(body).find("input[type='checkbox']:checked"), (i,n) => {
            downloadResource($(n).val() + ext, $(n).attr("fileid") + "-" + q);
        });
    }
}


function downloadResource(url, name){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = function(e) {
        if (this.status == 200) {
            // get binary data as a response
            var blob = this.response;
            const url = window.URL.createObjectURL(blob);
            var link = document.createElement('a');
            link.href= url;
            var filename = name + ".jpg";
            link.setAttribute('download', filename);
            evt = document.createEvent('MouseEvents');
            evt.initEvent('click', true, true);
            link.dispatchEvent(evt);
        }
    };
    xhr.send();
}


function getIndex() {
    var index = 1;
    return function() {
        return index ++;
    }
}

function bindChangeWorkEvents() {
    return false;
}



function bindChangeImg() {
    $(".btn-next").click(()=>{
        changeFocus();
    })
    $(".btn-prev").click(()=>{
        changeFocus();
    })
}