

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) {
  // create function which return resolved promise
  // with data:base64 string

  // here will be array of promisified functions
  const 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))
  }
  // array with base64 strings
  return await Promise.all(promises)
}

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) {
            const files_for_data = await fileListToBase64(fileList)
            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);
    //     };
    //
    // }










}


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: '/change_avatar_confirm/',
        type: "POST",
        // async: true,
        cache: false,
        processData: false,
        contentType: false,
        // enctype: 'json',
        data: JSON.stringify(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"});


        },
        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")
    }
}