profile_tabs_f_static_map = new Map([
    ['chats','chat'],
    ['support_tickets','support'],
    ['show_cur_subscribe','my_subscribe'],
    ['change_profile','change_profile'],
    ['new_route_view_customer','create_route_for_customer'],
    ['new_route_view_mover','create_route_for_mover'],
    ['get_routes','my_routes'],
    ['dashboard','dashboard']
])


function select_tab_profile (el,url,owner_type=null) {
    let data = {}
    let confirm_url = `/user_account/${url}/`
    if (url.includes('subscribe')){
        confirm_url = `/subscribes/${url}/`
    } else if (url.includes('new_route')){
        data = {
            'owner_type': owner_type
        }
    } else if (url.includes('get_routes')){
        confirm_url = `/routes/${url}/`
    }

    $.ajax({
        headers: { "X-CSRFToken": $('input[name=csrfmiddlewaretoken]').val() },
        url: confirm_url,
        type: "POST",
        // async: true,
        cache: false,
        processData: false,
        contentType: false,
        // enctype: 'json',
        data: JSON.stringify(data),
        success: function(data){
            document.querySelector(".info_profile").innerHTML = data.html;
            let list_div = document.querySelectorAll('.menu_profile div');
            list_div.forEach(el=>{ el.classList.remove('selected'); });
            el.classList.add('selected')
            // let body = document.querySelector("body")
            // body.style.overflow = "hidden"
            let confirm_url_f_lang_ru = ''
            let confirm_url_f_lang_en = ''
            if (owner_type){
                window.history.pushState(null, null, `/${document.documentElement.lang}/profile/page/${profile_tabs_f_static_map.get(`${url}_${owner_type}`)}/`)
                confirm_url_f_lang_ru = `/ru/profile/page/${profile_tabs_f_static_map.get(`${url}_${owner_type}`)}/`
                confirm_url_f_lang_en = `/en/profile/page/${profile_tabs_f_static_map.get(`${url}_${owner_type}`)}/`
            } else {
                window.history.pushState(null, null, `/${document.documentElement.lang}/profile/page/${profile_tabs_f_static_map.get(url)}/`)
                confirm_url_f_lang_ru = `/ru/profile/page/${profile_tabs_f_static_map.get(url)}/`
                confirm_url_f_lang_en = `/en/profile/page/${profile_tabs_f_static_map.get(url)}/`
            }
            document.querySelector("#ru_lang").href = confirm_url_f_lang_ru
            document.querySelector("#en_lang").href = confirm_url_f_lang_en


            middleWareJS()
            let user_type = getInfoAboutUser()
            if (user_type === 'mobile') {
                closeCurtain()
            } else {
                if (!window.location.href.includes('profile')){
                    closeCurtain()
                }
            }

        },
        error: function (data){
            console.log(data)

        }
    });
}

function getInfoAboutUser (){
    let user_type = ''
    if (screen.width <= 700){
        user_type = 'mobile'
    } else if (screen.width > 1024) {
        user_type = 'dectop'
    } else if (screen.width > 700 && screen.width < 1024) {
        user_type = 'laptop'
    }
    return user_type
}

function createTicketShow () {
    $.ajax({
        headers: { "X-CSRFToken": $('input[name=csrfmiddlewaretoken]').val() },
        url: '/messages/support_create_ticket_form/',
        type: "POST",
        // async: true,
        cache: false,
        processData: false,
        contentType: false,
        // enctype: 'json',
        // data: formData,
        success: function(data){

            document.querySelector(".insert-tech-place").innerHTML = data.html;
            middleWareJS()
        },
    });
}

function countLetters () {
    event.preventDefault()
    let area = document.querySelector(".el-form-create-ticket-textarea")
    let count = area.value.length
    let ins_area = document.querySelector(".letrs-count-span")
    // let spans = document.querySelectorAll(".ins-span")
    let count_div = ins_area.closest("div")
    if (count < 500) {
        let ins_area = document.querySelector(".letrs-count-span")
        ins_area.innerHTML = count
        if (count_div.classList.contains("disabled")){
            count_div.classList.remove("disabled")
        }
    }
    else {
        ins_area.innerHTML = '500'
        if (count_div.classList.contains("disabled")){
        //
        }
        else {
            count_div.classList.add("disabled")
        }


    }

}

// var input;


// function inputQuest (){
//     event.preventDefault()
//     // let input = document.querySelector(".create-ticket-file")
//     let input = document.createElement("input");
//     input.setAttribute("type", "file")
//     input.style.display = "none"
//     input.click()
//     // console.log("asd")
//
//     return input
// }
//
//
// function attachFileCreateTicket () {
//     let input = inputQuest()
//     let file = input.files[0]
//     // let file_url = URL.createObjectURL(file)
//
//
//
//     let data = file
//
// }
//
// function attachFilemeassge (e,el,id_ticket=null,sender,receiver) {
//     let input = inputQuest()
//     let file = input.files[0]
//     let int = setInterval(function (){
//         file = input.files[0]
//         if (file === undefined || file === null){
//         //
//         } else {
//
//             // let file_1 = URL.createObjectURL(file)
//             // let file_1 = URL.createObjectURL(file)
//             // var reader = new FileReader();
//             // var file = new ArrayBuffer(file);
//             // let file_1 = reader.readAsArrayBuffer(file)
//             // let file_1 = new ImageBitmap([file],{'type':file.type})
//             let file_1 = new Blob ([file],{'type':file.type})
//             // let url_ = URL.toDataURL(file_1)
//             // let file_2 = file_1.text()
//             // let reader = new ArrayBuffer(file_1);
//             // reader.Base64.encode(file_1)
//             let file_3 = URL.createObjectURL(file_1)
//             let file_4 = $(file_1).toDataURL
//             var reader = new FileReader();
//             reader.readAsBinaryString(file_1);
//             // let file_8 = new ImageBitmap(file,{'type':file.type})
//             // var fs = require('fs'),
//             data_1 = readFileSync(file);
//             console.log(data.toString('base64'));
//
//             // let file_url = URL.createObjectURL(file)
//
//             let data = reader
//             el.dataset['file_img'] = data
//             input.remove()
//             clearInterval(int)
//             sendMessage(id_ticket,sender,receiver,'pst_img')
//         }
//
//     },1000)
//
//
// }


// function getBase64(file,el) {
//     const reader = new FileReader()
//     let file_new = null
//     let file_new_p = new Promise(function () {
//         reader.readAsDataURL(file)
//         reader.onload = function () {
//             file_new = JSON.stringify({
//                 'file': reader.result,
//                 'file_type': el.type,
//                 'file_name': el.name
//             })
//
//         }
//
//     })
//     file_new_p.then(function (){
//         return file_new
//     })
// }
//
// async function fileListToBase64(fileList) {
//   const files_for_data = []
//
//   for (let i = 0; i < fileList.length; i++) {
//     let el = fileList[i]
//     files_for_data.push(getBase64(fileList[i],el))
//   }
//
//   return await Promise.all(files_for_data)
// }
function getBase64(file,el) {
    const reader = new FileReader()
    return new Promise(resolve => {
      reader.onload = ev => {
            resolve(file_new = JSON.stringify({
                'file': reader.result,
                'file_type': el.type,
                'file_name': el.name,
                'file_size': el.size
               })
            )
      }
      reader.readAsDataURL(file)

    })
}

async function fileListToBase64(fileList=null,file=null) {
  // create function which return resolved promise
  // with data:base64 string

  // here will be array of promisified functions
  const promises = []
  const promise = {}
  let return_ = null
  if (fileList) {
      return_ = promises
      // loop through fileList with for loop
      for (let i = 0; i < fileList.length; i++) {
         let el = fileList[i]
         promises.push(getBase64(fileList[i], el))
      }
      return await Promise.all(return_)
  } else if (file){
      const promise = {}
      return_ = promise
      promise[file.name] = getBase64(file, file)
      return await return_[file.name]
  }

      // array with base64 strings
  // return await Promise.all(return_)
}

async function attachFilemeassge (el,id_ticket=null,sender=null,receiver=null,change_avatar=null){
    // let file = el.files[0];
    let fileList = el.files;
    if (!change_avatar) {
        if (el.files.length > 0) {
            const files_for_data = await fileListToBase64(fileList)
            let data = files_for_data
            sendMessage(id_ticket, sender, receiver, data)
        }
    } else {
        if (el.files.length > 0) {
            let file = fileList[0]
            const files_for_data = await fileListToBase64(null,file)
            let data = files_for_data
            return data
        }
    }
    // let reader = new FileReader();
    // let mas_for_for_each = []

    // for (let i = 0;i < el.files.length;i++){
    //     let file_for_data_url_opert = el.files[i]
    //
    //     reader.readAsDataURL(file_for_data_url_opert);
    //     reader.onload = function() {
    //         // console.log(reader.result);
    //         let file = JSON.stringify({
    //             'file': reader.result,
    //             'file_type': el.files[i].type,
    //             'file_name': el.files[i].name
    //         })
    //         files_for_data.push(file)
    //     };
    //
    //     reader.onerror = function() {
    //         console.log(reader.error);
    //     };
    //
    // }










}

function change_profile_confirm (el){
    event.preventDefault()
    let form = el.form
    let changed_elements = {}
    for (let i = 0;i < form.length;i++){
        let cur_el = form[i]
        if (cur_el.localName !== 'button'){
            let new_val = cur_el.value
            let dataset = cur_el.dataset
            let old_val = ''
            if (dataset){
                old_val = dataset['initialValue']
            }
            // if (old_val){
                if (old_val === new_val){
                //
                } else {
                    changed_elements[cur_el.name] = cur_el.value
                }
        }
        // }
    }


    $.ajax({
        headers: { "X-CSRFToken": $('input[name=csrfmiddlewaretoken]').val() },
        url: '/user_account/change_profile_confirm/',
        type: "POST",
        // async: true,
        cache: false,
        processData: false,
        contentType: false,
        // enctype: 'json',
        data: JSON.stringify(changed_elements),
        success: function(data){
            middleWareJS()

            document.querySelector(".info_profile").innerHTML = data.html;

        },
        error: function (data){

            document.querySelector(".avatar_user_profile").innerHTML = data.responseJSON.html;

        }
    });
}



async function upload_photo_f_profile (el,files) {
    // if (!files){
    const data = await attachFilemeassge(el, null, null, null, 'avatar')
    // }
    // if (files){
    $.ajax({
        headers: { "X-CSRFToken": $('input[name=csrfmiddlewaretoken]').val() },
        url: '/user_account/change_avatar_confirm/',
        type: "POST",
        // async: true,
        cache: false,
        processData: false,
        contentType: false,
        // enctype: 'json',
        data: data,
        success: function(data){
            middleWareJS()

            document.querySelector(".avatar_user_profile").src = data.url;

        },
        error: function (data){

            document.querySelector(".avatar_user_profile").innerHTML = data.responseJSON.html;

        }
    });
    // }
}




function createTicket (el) {
    event.preventDefault()
    let form = el.form
    var formData = new FormData(form);
    $.ajax({
        headers: { "X-CSRFToken": $('input[name=csrfmiddlewaretoken]').val() },
        url: '/messages/create_ticket/',
        type: "POST",
        // async: true,
        cache: false,
        processData: false,
        contentType: false,
        // enctype: 'json',
        data: formData,
        success: function(data){
            middleWareJS()

            document.querySelector(".insert-tech-place").innerHTML = data.html;

        },
        error: function (data){

            document.querySelector(".insert-tech-place").innerHTML = data.responseJSON.html;

        }
    });
}


function selectedUserMessenger (ticket_id=null,user_id=null){
    let loader = document.querySelector(".loader_chat_f_sw_chats")
    let block_chat = document.querySelector(".block-chat")
    if (loader){
        loader.classList.toggle("show")
        if (block_chat) {
            block_chat.innerHTML = null
        }
    }
    let data = null
    let url = null
    if (ticket_id !== null){
        data = {
            'ticket_id': ticket_id
        }
        url = 'support_show_chat_by_ticket/'
    } else if (user_id !== null){
        data = {
            'user_id': user_id
        }
        url = 'show_chat_w_user/'
    }

    $.ajax({
        headers: { "X-CSRFToken": $('input[name=csrfmiddlewaretoken]').val() },
        url: '/messages/' + url,
        type: "POST",
        // async: true,
        cache: false,
        processData: false,
        contentType: false,
        // enctype: 'json',
        data: JSON.stringify(data),
        success: function(data){
            middleWareJS()
            if (loader){
                loader.classList.toggle("show")
            }
            document.querySelector(".info_profile").innerHTML = data.html;
            document.querySelector(".enter-message-inp").focus()
            document.querySelector(".tab_user_messanger.select").scrollIntoView({behavior: "smooth",block:'nearest',inline:'nearest'});

            let user_type = getInfoAboutUser()
            let curt_f_close = getCurtainWIncreaceZindex(document.querySelectorAll('.curtain'))
            if (user_type === 'mobile' || user_type === 'laptop') {
                closeCurtain('left')
            } else if (!window.location.href.includes('profile')){
                closeCurtain()
            }

        },
        error: function (data){

            document.querySelector(".info_profile").innerHTML = data.responseJSON.html;

        }
    });
}


function sendMessage(id_ticket=null,sender,receiver,files=null){
    // import {sendMessageSocket} from "./chat_sockets";
    if (!files){
        event.preventDefault()
    }
    let text = document.querySelector(".enter-message-inp").value
    document.querySelector(".enter-message-inp").value = null
    let img = document.querySelector(".attach-file-btn-message").dataset["file_img"]


    if (files){

        let data = {}
            if (id_ticket === null){
                data = {
                    'sender': sender,
                    'receiver': receiver,
                    'text': '',
                    'files': files
                }
            } else {
                 data = {
                    'ticket_id': id_ticket,
                    'sender': sender,
                    'receiver': receiver,
                    'text': '',
                    'files': files
                }
            }




        sendMessageSocket(data,img)

    } else {

        if (text.length === 0){
        //
        }
        else {
            let data = {}
            if (id_ticket === null){
                data = {
                    'sender': sender,
                    'receiver': receiver,
                    'text': text,
                    'img': img
                }
            } else {
                 data = {
                    'ticket_id': id_ticket,
                    'sender': sender,
                    'receiver': receiver,
                    'text': text,
                    'img': img
                }
            }



            // $.ajax({
            //     headers: { "X-CSRFToken": $('input[name=csrfmiddlewaretoken]').val() },
            //     url: '/ru/messages/send_msg/',
            //     type: "POST",
            //     // async: true,
            //     cache: false,
            //     processData: false,
            //     contentType: false,
            //     // enctype: 'json',
            //     data: JSON.stringify(data),
            //     success: function(data){
            //         middleWareJS()
            //
            //         document.querySelector(".container-messages").innerHTML = data.html;
            //         document.querySelector(".enter-message-inp").focus()
            //
            //     },
            //     error: function (data){
            //
            //         document.querySelector(".container-messages").innerHTML = data.responseJSON.error;
            //         document.querySelector(".enter-message-inp").focus()
            //     }
            // });

            sendMessageSocket(data)
        }
    }
}

function openTicket (ticket_id){
    let data = {
        'ticket_id': ticket_id
    }

    $.ajax({
        headers: { "X-CSRFToken": $('input[name=csrfmiddlewaretoken]').val() },
        url: '/messages/support_show_chat_by_ticket/',
        type: "POST",
        // async: true,
        cache: false,
        processData: false,
        contentType: false,
        // enctype: 'json',
        data: JSON.stringify(data),
        success: function(data){
            middleWareJS()

            document.querySelector(".info_profile").innerHTML = data.html;

        },
        error: function (data){

            document.querySelector(".info_profile").innerHTML = data.responseJSON.html;

        }
    });
}

function sendMessageEnter (e,id_ticket,sender,receiver){
    if (e.keyCode === 13){
        sendMessage(id_ticket,sender,receiver)
    }
    else {
    //
    }
}

function send_subscribe (id){
    let data  = {
        'subscribe_id':id
    }
    $.ajax({
        headers: { "X-CSRFToken": $('input[name=csrfmiddlewaretoken]').val() },
        url: '/subscribes/subscribe_now/',
        type: "POST",
        // async: true,
        cache: false,
        processData: false,
        contentType: false,
        // enctype: 'json',
        data: JSON.stringify(data),
        success: function(data){

            document.querySelector(".info_profile").innerHTML = data.html;

        },
        error: function (data){

            document.querySelector(".info_profile").innerHTML = data.responseJSON.html;

        }
    });
}


function show_header_list () {
    let el = document.querySelector(".menu_profile_btn")
    if (el) {
        el.classList.toggle("show")
        closeCurtain()
    }
}

function closeCurtain (left,right) {
    if (left){
        let left = document.querySelector(".curtain.left")
        open_curtain(left,null,null,'close')
    } else if (right){
        let right = document.querySelector(".curtain.right")
        open_curtain(null,right,null,'close')
    } else {
        let curtain = getOpenCurtain()
        if (curtain) {
            open_curtain(null, null, null, 'close')
        }
    }
}


function open_curtain (left=null,right=null,overlay=null,close=null){
    let page_profile = true
    let curtain_name = ''
    let curtain = ''
    let left_curtain = document.querySelector(".menu_buttons.left")
    let right_curtain = document.querySelector(".menu_buttons.right")

    if (left || right){
        if (left){
            if (left_curtain){
                curtain = left_curtain
                newCurtainZIndex(curtain)
                if (right_curtain) {
                    right_curtain.style.zIndex = '99'
                    curtain_name = curtain.dataset['name']
                }
            }

        } else if (right) {
            if (right_curtain){
                curtain = right_curtain
                newCurtainZIndex(curtain)
                if (left_curtain) {
                    left_curtain.style.zIndex = '99'
                    curtain_name = curtain.dataset['name']
                }
            }
        }
    } else {
        curtain = getOpenCurtain()
        curtain_name = getInfoCurtain(null,null,'name')['name']
    }
    if (!curtain){
        curtain = getCurtainWIncreaceZindex(left_curtain,right_curtain)
    }
    let body = document.querySelector('body')
    if (curtain[0]){
        let type_curt = getTypeOfData(curtain)
        if (type_curt === 'object'){
            curtain = curtain[0]
        }
    }
    if (close){
        // curtain = getOpenCurtain()

        let handler_text = curtain.querySelector('.text_f_curtain')

        handler_text.innerHTML = curtain_name
        curtain.classList.remove("open")
        curtain.classList.add("close")

        let user_type = getInfoAboutUser()
        if (user_type === 'mobile') {
            curtain.classList.remove("open")
            curtain.classList.add("close")
            closeOverlay()
        } else {
            if (!window.location.href.includes('profile')){
            //
            }
        }
    } else {

        let user_type = getInfoAboutUser()
        if (user_type === 'mobile' || !window.location.host.includes('profile') || user_type === 'laptop' ) {
            curtain.classList.toggle("open")
            curtain.classList.toggle("close")
            newCurtainZIndex()
            let curtain_check = getOpenCurtain()
            if (curtain_check.length > 1){
                let curtain_old = getCurtainWIncreaceZindex(curtain_check,'decreace')['increace']
                curtain_old.classList.toggle("close")
                curtain_old.classList.toggle("open")
            }
            if (curtain_check.length > 0){
                let overlay = document.querySelector('.block_overlay.show')
                if (!overlay){
                    let overlay_clear = document.querySelector(".block_overlay")
                    overlay_clear.classList.toggle('show')
                    overlay_clear.classList.toggle('hidden')
                }
            } else {

                closeOverlay()

            }
        } else {
            if (!window.location.href.includes('profile')){
            //
            }
        }


        let handler_text = curtain.querySelector('.text_f_curtain')
        if (curtain.classList.contains('open')){
            handler_text.innerHTML = 'Закрыть'
            handler_text.style.fontSize = '13px'
        } else {
            handler_text.innerHTML = curtain_name
            handler_text.style.fontSize = '16px'
        }

        if (!curtain.classList.contains('open')){
            body.style.overflowY = ''
        } else {
            body.style.overflowY = 'hidden'
        }

    }


}

function closeOverlay () {
    let curt = getOpenCurtain()
    if (curt.length > 1){
    //     nothing to do
    } else {
        let overlay = document.querySelector(".block_overlay")
        overlay.classList.add('hidden')
        overlay.classList.remove('show')
    }
}

function newCurtainZIndex (curtain) {
    let cur_curtain = ''
    if (curtain){
        cur_curtain = curtain
    } else {
        cur_curtain = getOpenCurtain()[0]
    }
    if (cur_curtain){
        cur_curtain.style.zIndex = '101'
    }

}

function getInfoCurtain (curtain,zIndex,name) {
    let data = {}
    let curtain_f_w = null
    if (curtain){
        let type_curt = getTypeOfData(curtain)
        if (curtain[0] && type_curt === 'object'){
            curtain_f_w = curtain[0]
        } else {
            curtain_f_w = curtain
        }


    } else {
        curtain_f_w = getOpenCurtain()
        let type_curt = getTypeOfData(curtain_f_w)
        if (curtain_f_w[0]){
            if (type_curt === 'object'){
                curtain_f_w = curtain_f_w[0]
            }
        }

    }
    if (name){
        let dataset = curtain_f_w.dataset
        let name = ''
        if (dataset){
            name = dataset['name']
            data['name'] = name
        }
    }
    if (zIndex){
        if (curtain_f_w.style.zIndex){
            data['zIndex'] = curtain_f_w.style.zIndex
        } else{
            data['zIndex'] = 'z-index not finded'
        }

    }
    return data
}

function getOpenCurtain () {
    let curtains = document.querySelectorAll(".curtain.open")
    if (!curtains){
        curtains = document.querySelector('.curtain')
        console.log(`not finded open curtain choice first curtain named=${curtains.dataset['name']}`)
    }
    return curtains
}

function getTypeOfData (data) {
    let type = typeof data
    return type
}

function getCurtainWIncreaceZindex (curtains,decreace) {
    let first = getInfoCurtain(curtains[0],'zIndex')
    let second =  getInfoCurtain(curtains[1],'zIndex')
    let el_increace = ''
    if (first['zIndex'] > second['zIndex']){
        el_increace = first
        if (decreace){
            return {
                'increace': curtains[0],
                'decreace': curtains[1]
            }
        } else {
            return curtains[0]
        }

    }
    if (second['zIndex'] > first['zIndex']){
        el_increace = second
        if (decreace){
            return {
                'increace': curtains[1],
                'decreace': curtains[0]
            }
        } else {
            return curtains[1]
        }

    }

}
