import { Controller } from '@hotwired/stimulus';
import { MvMessage } from '../scripts/mvMessage';
import {Modal} from "bootstrap";
import axios from "axios";
import {hide} from "@popperjs/core";


/*
 * This is an example Stimulus controller!
 *
 * Any element with a data-controller="hello" attribute will cause
 * this controller to be executed. The name "hello" comes from the filename:
 * hello_controller.js -> "hello"
 *
 * Delete this file or adapt it for your use!
 */
export default class extends Controller {

    static values = {
        id: String,
        connectorid: String,
        tagid: String,
        visualtagid: String
    }



    connect() {
        let message = new MvMessage();

        const urlParams = new URLSearchParams(window.location.search);
        const redirect_status = urlParams.get('redirect_status');
        if(redirect_status==="succeeded"){
            $('#startCharge').attr('disabled',false)
            message.showMessage('success', 'Le paiement est validé, vous pouvez lancer la charge')
        }
        axios.get('/json/borne/price?idBorne='+this.idValue+'&idConnector='+this.connectoridValue, {})
        .then(function (response) {
            let def = response.data.pricingDefinitions[0]
            
  
            document.getElementById('flatPrice-'+response.data.pricingContext.connectorId).innerHTML=def.dimensions.flatFee.price.toString() + ' <i class="fa-solid fa-euro-sign"></i>';
            document.getElementById('energyPrice-'+response.data.pricingContext.connectorId).innerHTML=def.dimensions.energy.price.toString() + ' <i class="fa-solid fa-euro-sign"></i>';
        })
        .catch(function (error) {
        })
        .then(function () {
            // dans tous les cas
        });

        $(document).on('click','#startCharge',()=>{
            // const email = document.getElementById('email').val;
            const email = $('#email').val();
            const stratBtn = $('#startCharge');
            localStorage.setItem('email',email);
            stratBtn.html('<i class="fa-solid fa-circle-notch fa-spin"></i> Lancer la charge');
            if (email ==='' || email === undefined){
                message.showMessage('warning','Veuillez entrer votre adresse e-mail !')
                stratBtn.html('<i class="fa-solid fa-circle-play"></i> Lancer la charge')
            }else{
                sessionStorage.setItem("email", email);
                sessionStorage.setItem("idBorne", this.idValue);
                sessionStorage.setItem("idConnector", this.connectoridValue);
                sessionStorage.setItem("idVisualTag", this.visualtagid);
                //*************************************************************************************
                $.ajax({
                    method: "POST",
                    url: '/json/borne/start' ,
                    data: {
                        idBorne: this.idValue,
                        idConnector: this.connectoridValue,
                        idTag: this.tagidValue,
                        idVisualTag: this.visualtagid,
                        email: email,
                    }
                })
                    .done(function( response ) {
                        if (response.success === true){
                            message.showMessage('success',response.message);
                            $('#borneBottom').html(response.content);
                            setTimeout(()=>{
                                sendEmail('start');
                            },3000)
                        }else{
                            message.showMessage('danger',response.message);
                        }
                    })
                    .always(stratBtn.html('<i class="fa-solid fa-circle-play"></i> Lancer la charge'));
                //********************************************
                // axios.get('/json/borne/start?idBorne='+this.idValue+'&idConnector='+this.connectoridValue+'&idTag='+this.tagidValue+'&idVisualTag='+this.visualtagid, {})
                //     .then((response)=>{
                //         console.log(response);
                //         if (response.data.success === true){
                //             message.showMessage('success',response.data.message);
                //             $('#borneBottom').html(response.data.content);
                //         }else{
                //             message.showMessage('danger',response.data.message);
                //         }
                //     })
                //     .catch()
                //     .finally(
                //         stratBtn.html('<i class="fa-solid fa-circle-play"></i> Lancer la charge')
                //     )
            }
        })
        $(document).on('click','#stopCharge',()=>{
            const pincode = $('#pinCode').val();
            // const pincode = document.getElementById('pinCode').val;
            const chargeBtn = $('#stopCharge');
            chargeBtn.html('<i class="fa-solid fa-circle-notch fa-spin"></i> Stopper la charge')
            const email = localStorage.getItem('email');
            if (pincode === '' || pincode === undefined) {
                message.showMessage('warning', 'Veuillez entrer un code !')
                chargeBtn.html('<i class="fa-solid fa-circle-stop"></i> Stopper la charge ')
            }else{
                //----------------------------------------------------------------------

                $.ajax({
                    method: "POST",
                    url: '/json/borne/stop' ,
                    data: {
                        transaction: $('#pinCode').val(),
                        email: email,
                    }
                })
                    .done(function( response ) {
                        if (response.success === true) {
                        message.showMessage('success', response.message);
                        $('#borneBottom').html(response.content);
                        setTimeout(()=>{
                            sendEmail('stop', response.transaction)
                        },2000)
                    } else {
                        message.showMessage('danger', response.message);
                    }
                    })
                    .always(chargeBtn.html('<i class="fa-solid fa-circle-stop"></i> Stopper la charge '));
                //----------------------------------------------------------------------
                // axios.get('/json/borne/stop?transaction=' + $('#pinCode').val(), {})
                //     .then((response) => {
                //         if (response.data.success === true) {
                //             console.log(response);
                //             message.showMessage('success', response.data.message);
                //             $('#borneBottom').html(response.data.content);
                //         } else {
                //             message.showMessage('danger', response.data.message);
                //         }
                //     })
                //     .catch()
                //     .finally(
                //         chargeBtn.html('<i class="fa-solid fa-circle-stop"></i> Stopper la charge ')
                //     )
            }
        })
        $(document).on('click','#viewCharge',()=>{
            const pincode = $('#pinCode').val();
            // const pincode = document.getElementById('pinCode').val;
            const viewBtn = $('#viewCharge');
            viewBtn.html('<i class="fa-solid fa-circle-notch fa-spin"></i> Suivre la charge')
            if (pincode === '' || pincode === undefined) {
                message.showMessage('warning', 'Veuillez entrer un code !')
                viewBtn.html('<i class="fa-solid fa-circle-stop"></i> Suivre la charge ')
            }else{
                updateView();
            }
        })
        function sendEmail(typeEmail,transaction='' ){

            $.ajax({
                method: "POST",
                url: '/json/borne/email' ,
                data: {
                    idBorne: sessionStorage.getItem('idBorne'),
                    idConnector: sessionStorage.getItem('idConnector'),
                    email: sessionStorage.getItem('email'),
                    idTransaction: transaction,
                    typeEmail:typeEmail
                }
            })
                .done(function( response ) {
                    if (response.success === true) {
                        message.showMessage('success', response.message);
                        if (typeEmail==='start'){
                            updateIntent(sessionStorage.getItem('email'),response.data.transaction)
                        }
                    } else {
                        message.showMessage('danger', response.message);
                    }
                })
            //---------------------------------

        }
        function updateView() {
            axios.get('/json/borne/view?transaction=' + $('#pinCode').val(), {})
                .then((response) => {
                    if (response.data.success === true) {
                        $('#borneBottom').html(response.data.content);
                        setTimeout(()=>{
                            updateView()
                        },5000)
                    } else {
                        message.showMessage('danger', response.data.message);
                    }
                })
                .catch()
                .finally(
                    viewBtn.html('<i class="fa-solid fa-circle-stop"></i> Suivre la charge ')
                )
        }
        $(document).on('click','#payButton',()=>{
            $('#startCharge').attr('disabled',false);
            $('#payModal').modal('hide');
        })
        function updateIntent(email,transaction) {
            console.log('tr');
            console.log(transaction)
            $.ajax({
                method: "POST",
                url: '/stripe/update' ,
                data: {
                    email:email,
                    transaction:transaction,
                    intent: urlParams.get('payment_intent'),
                }
            })
                .done(function( response ) {

                })
                .fail()
                .always();
        }
    }
}
